aboutsummaryrefslogtreecommitdiff
path: root/lib/http
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2024-03-03 04:59:34 +0700
committerShulhan <ms@kilabit.info>2024-03-05 14:53:12 +0700
commit2fa7605727e90ca323b7b24168632e485d74c583 (patch)
tree3533df0fc07ef96b1564736926cc3310994be515 /lib/http
parentb921ebfb3e81b367ff24305eb18c5dd073b38635 (diff)
downloadpakakeh.go-2fa7605727e90ca323b7b24168632e485d74c583.tar.xz
all: comply with linter recommendations #2
HTTP request now implicitly create request with context. Any false positive related to not closing HTTP response body has been annotated with "nolint:bodyclose". In the example code, use consistent "// Output:" comment format, by prefixing with single space. Any comment on code now also prefixing with single space. An error returned without variables now use [errors.New] instead of [fmt.Errorf]. Any error returned using [fmt.Errorf] now wrapped using "%w" instead of "%s". Also, replace error checking using [errors.Is] or [errors.As], instead of using equal/not-equal operator. Any statement like "x = x OP y" now replaced with "x OP= y". Also, swap statement is simplified using "x, y = y, x". Any switch statement with single case now replaced with if-condition. Any call to defer on function or program that call [os.Exit], now replaced by calling the deferred function directly. Any if-else condition now replaced with switch statement, if possible.
Diffstat (limited to 'lib/http')
-rw-r--r--lib/http/client.go26
-rw-r--r--lib/http/client_request.go5
-rw-r--r--lib/http/client_test.go4
-rw-r--r--lib/http/endpoint_example_test.go13
-rw-r--r--lib/http/endpoint_response_example_test.go6
-rw-r--r--lib/http/example_server_test.go8
-rw-r--r--lib/http/form.go6
-rw-r--r--lib/http/form_example_test.go30
-rw-r--r--lib/http/http_test.go5
-rw-r--r--lib/http/range.go7
-rw-r--r--lib/http/response.go13
-rw-r--r--lib/http/response_test.go2
-rw-r--r--lib/http/server.go6
-rw-r--r--lib/http/server_test.go105
-rw-r--r--lib/http/sseclient/sseclient.go2
15 files changed, 156 insertions, 82 deletions
diff --git a/lib/http/client.go b/lib/http/client.go
index 9b59fa6d..2f9c4336 100644
--- a/lib/http/client.go
+++ b/lib/http/client.go
@@ -10,6 +10,7 @@ import (
"compress/flate"
"compress/gzip"
"compress/lzw"
+ "context"
"crypto/tls"
"encoding/json"
"errors"
@@ -262,9 +263,12 @@ func (client *Client) GenerateHTTPRequest(
}
rpath = path.Join(`/`, rpath)
- var fullURL = client.opts.ServerURL + rpath
+ var (
+ fullURL = client.opts.ServerURL + rpath
+ ctx = context.Background()
+ )
- req, err = http.NewRequest(method.String(), fullURL, body)
+ req, err = http.NewRequestWithContext(ctx, method.String(), fullURL, body)
if err != nil {
return nil, fmt.Errorf("%s: %w", logp, err)
}
@@ -426,9 +430,15 @@ func (client *Client) doRequest(
res *http.Response, resBody []byte, err error,
) {
rpath = path.Join(`/`, rpath)
- var fullURL = client.opts.ServerURL + rpath
- httpReq, err := http.NewRequest(httpMethod, fullURL, body)
+ var (
+ fullURL = client.opts.ServerURL + rpath
+ ctx = context.Background()
+
+ httpReq *http.Request
+ )
+
+ httpReq, err = http.NewRequestWithContext(ctx, httpMethod, fullURL, body)
if err != nil {
return nil, nil, err
}
@@ -542,11 +552,11 @@ func (client *Client) uncompress(res *http.Response, body []byte) (
// GenerateFormData generate multipart/form-data body from params.
func GenerateFormData(params map[string][]byte) (contentType, body string, err error) {
var (
- sb = new(strings.Builder)
- w = multipart.NewWriter(sb)
+ sb = new(strings.Builder)
+ w = multipart.NewWriter(sb)
+ listKey = make([]string, 0, len(params))
- k string
- listKey []string
+ k string
)
for k = range params {
listKey = append(listKey, k)
diff --git a/lib/http/client_request.go b/lib/http/client_request.go
index a1a2d7ec..42b330de 100644
--- a/lib/http/client_request.go
+++ b/lib/http/client_request.go
@@ -6,6 +6,7 @@ package http
import (
"bytes"
+ "context"
"encoding/json"
"fmt"
"io"
@@ -131,7 +132,9 @@ func (creq *ClientRequest) toHTTPRequest(client *Client) (httpReq *http.Request,
}
}
- httpReq, err = http.NewRequest(creq.Method.String(), path.String(), body)
+ var ctx = context.Background()
+
+ httpReq, err = http.NewRequestWithContext(ctx, creq.Method.String(), path.String(), body)
if err != nil {
return nil, fmt.Errorf("%s: %w", logp, err)
}
diff --git a/lib/http/client_test.go b/lib/http/client_test.go
index b92b3b11..56ff4333 100644
--- a/lib/http/client_test.go
+++ b/lib/http/client_test.go
@@ -44,7 +44,7 @@ func TestClient_Download(t *testing.T) {
},
Output: &out,
},
- expError: fmt.Sprintf("%s: 404 Not Found", logp),
+ expError: logp + `: 404 Not Found`,
}, {
desc: "With redirect",
req: DownloadRequest{
@@ -82,7 +82,7 @@ func TestClient_Download(t *testing.T) {
for _, c := range cases {
out.Reset()
- _, err = client.Download(c.req)
+ _, err = client.Download(c.req) //nolint: bodyclose
if err != nil {
test.Assert(t, c.desc+`: error`, c.expError, err.Error())
continue
diff --git a/lib/http/endpoint_example_test.go b/lib/http/endpoint_example_test.go
index 6cf9b515..2ca02de3 100644
--- a/lib/http/endpoint_example_test.go
+++ b/lib/http/endpoint_example_test.go
@@ -5,6 +5,7 @@
package http
import (
+ "errors"
"fmt"
"log"
"net/http"
@@ -26,7 +27,7 @@ func ExampleEndpoint_errorHandler() {
RequestType: RequestTypeQuery,
ResponseType: ResponseTypePlain,
Call: func(epr *EndpointRequest) ([]byte, error) {
- return nil, fmt.Errorf(epr.HTTPRequest.Form.Get(`error`))
+ return nil, errors.New(epr.HTTPRequest.Form.Get(`error`))
},
ErrorHandler: func(epr *EndpointRequest) {
epr.HTTPWriter.Header().Set(HeaderContentType, ContentTypePlain)
@@ -59,16 +60,18 @@ func ExampleEndpoint_errorHandler() {
params := url.Values{}
params.Set("error", "400:error with status code")
- httpres, resbody, err := client.Get(`/`, nil, params)
+ httpres, resbody, err := client.Get(`/`, nil, params) //nolint: bodyclose
if err != nil {
- log.Fatal(err)
+ log.Println(err)
+ return
}
fmt.Printf("%d: %s\n", httpres.StatusCode, resbody)
params.Set("error", "error without status code")
- httpres, resbody, err = client.Get(`/`, nil, params)
+ httpres, resbody, err = client.Get(`/`, nil, params) //nolint: bodyclose
if err != nil {
- log.Fatal(err)
+ log.Println(err)
+ return
}
fmt.Printf("%d: %s\n", httpres.StatusCode, resbody)
diff --git a/lib/http/endpoint_response_example_test.go b/lib/http/endpoint_response_example_test.go
index 1fab11a4..e9944edb 100644
--- a/lib/http/endpoint_response_example_test.go
+++ b/lib/http/endpoint_response_example_test.go
@@ -74,7 +74,7 @@ func ExampleEndpointResponse() {
params := url.Values{}
// Test call endpoint without "id" parameter.
- _, resBody, err := cl.Get("/", nil, params)
+ _, resBody, err := cl.Get("/", nil, params) //nolint: bodyclose
if err != nil {
log.Fatal(err)
}
@@ -83,7 +83,7 @@ func ExampleEndpointResponse() {
// Test call endpoint with "id" parameter set to "0", it should return
// HTTP status 500 with custom message.
params.Set("id", "0")
- _, resBody, err = cl.Get("/", nil, params)
+ _, resBody, err = cl.Get("/", nil, params) //nolint: bodyclose
if err != nil {
log.Fatal(err)
}
@@ -91,7 +91,7 @@ func ExampleEndpointResponse() {
// Test with "id" parameter is set.
params.Set("id", "1000")
- _, resBody, err = cl.Get("/", nil, params)
+ _, resBody, err = cl.Get("/", nil, params) //nolint: bodyclose
if err != nil {
log.Fatal(err)
}
diff --git a/lib/http/example_server_test.go b/lib/http/example_server_test.go
index c9575172..74a60f2a 100644
--- a/lib/http/example_server_test.go
+++ b/lib/http/example_server_test.go
@@ -60,7 +60,8 @@ func ExampleServer_customHTTPStatusCode() {
err = srv.registerPost(epCustom)
if err != nil {
- log.Fatal(err)
+ log.Println(err)
+ return
}
// Wait for the server fully started.
@@ -71,9 +72,10 @@ func ExampleServer_customHTTPStatusCode() {
}
client := NewClient(clientOpts)
- httpRes, resBody, err := client.PostJSON(epCustom.Path, nil, nil)
+ httpRes, resBody, err := client.PostJSON(epCustom.Path, nil, nil) //nolint: bodyclose
if err != nil {
- log.Fatal(err)
+ log.Println(err)
+ return
}
fmt.Printf("%d\n", httpRes.StatusCode)
diff --git a/lib/http/form.go b/lib/http/form.go
index 329d0557..824a683b 100644
--- a/lib/http/form.go
+++ b/lib/http/form.go
@@ -190,10 +190,8 @@ func UnmarshalForm(in url.Values, out interface{}) (err error) {
} else {
vout = vout.Elem()
}
- } else {
- if rkind != reflect.Struct {
- return fmt.Errorf("%s: expecting *T or **T got %T", logp, out)
- }
+ } else if rkind != reflect.Struct {
+ return fmt.Errorf(`%s: expecting *T or **T got %T`, logp, out)
}
listFields = reflect.VisibleFields(rtype)
diff --git a/lib/http/form_example_test.go b/lib/http/form_example_test.go
index 02f89c4d..50994fa4 100644
--- a/lib/http/form_example_test.go
+++ b/lib/http/form_example_test.go
@@ -42,8 +42,8 @@ func ExampleMarshalForm() {
fmt.Println(out.Encode())
- //Output:
- //Bool=true&Int=1&big.Rat=1.2345&bytes=bytes&f32=3.2&f64=6.4&notset=0&string=a_string&uint8=2
+ // Output:
+ // Bool=true&Int=1&big.Rat=1.2345&bytes=bytes&f32=3.2&f64=6.4&notset=0&string=a_string&uint8=2
}
func ExampleUnmarshalForm() {
@@ -90,9 +90,9 @@ func ExampleUnmarshalForm() {
fmt.Printf("%+v\n", ptrOut)
}
- //Output:
- //{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true}
- //&{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true}
+ // Output:
+ // {Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true}
+ // &{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true}
}
func ExampleUnmarshalForm_error() {
@@ -133,10 +133,10 @@ func ExampleUnmarshalForm_error() {
fmt.Println(out)
}
- //Output:
- //UnmarshalForm: expecting *T got http.T
- //UnmarshalForm: *http.T is not initialized
- //{0}
+ // Output:
+ // UnmarshalForm: expecting *T got http.T
+ // UnmarshalForm: *http.T is not initialized
+ // {0}
}
@@ -176,9 +176,9 @@ func ExampleUnmarshalForm_slice() {
fmt.Printf("%+v\n", ptrSliceOut)
}
- //Output:
- //{NotSlice:first SliceString:[multi value] SliceInt:[123 456]}
- //&{NotSlice:first SliceString:[multi value] SliceInt:[123 456]}
+ // Output:
+ // {NotSlice:first SliceString:[multi value] SliceInt:[123 456]}
+ // &{NotSlice:first SliceString:[multi value] SliceInt:[123 456]}
}
func ExampleUnmarshalForm_zero() {
@@ -232,7 +232,7 @@ func ExampleUnmarshalForm_zero() {
fmt.Printf("%+v\n", out)
}
- //Output:
- //{Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true}
- //{Rat:0 String: Bytes:[] Int:0 F64:0 F32:0 NotSet:0 Uint8:0 Bool:false}
+ // Output:
+ // {Rat:1.2345 String:a_string Bytes:[98 121 116 101 115] Int:1 F64:6.4 F32:3.2 NotSet:0 Uint8:2 Bool:true}
+ // {Rat:0 String: Bytes:[] Int:0 F64:0 F32:0 NotSet:0 Uint8:0 Bool:false}
}
diff --git a/lib/http/http_test.go b/lib/http/http_test.go
index 47c03894..21e22216 100644
--- a/lib/http/http_test.go
+++ b/lib/http/http_test.go
@@ -68,7 +68,7 @@ func TestMain(m *testing.M) {
Address: serverAddress,
}
- testServerURL = fmt.Sprintf("http://" + serverAddress)
+ testServerURL = `http://` + serverAddress
testServer, err = NewServer(opts)
if err != nil {
@@ -166,7 +166,8 @@ func registerEndpoints() {
// skip certain header keys.
func dumpHTTPResponse(httpRes *http.Response, skipHeaders []string) string {
var (
- keys []string
+ keys = make([]string, 0, len(httpRes.Header))
+
hkey string
)
for hkey = range httpRes.Header {
diff --git a/lib/http/range.go b/lib/http/range.go
index 3292ccb0..03a7d484 100644
--- a/lib/http/range.go
+++ b/lib/http/range.go
@@ -214,15 +214,16 @@ func (r *Range) Add(start, end *int64) bool {
if start == nil && end == nil {
return false
}
- if start == nil {
+ switch {
+ case start == nil:
if *end <= 0 {
return false
}
- } else if end == nil {
+ case end == nil:
if *start < 0 {
return false
}
- } else {
+ default:
if *start < 0 || *end < 0 || *end < *start {
return false
}
diff --git a/lib/http/response.go b/lib/http/response.go
index c46972ee..9525799d 100644
--- a/lib/http/response.go
+++ b/lib/http/response.go
@@ -6,6 +6,7 @@ package http
import (
"bytes"
+ "errors"
"fmt"
"net/http"
"strconv"
@@ -22,7 +23,7 @@ func ParseResponseHeader(raw []byte) (resp *http.Response, rest []byte, err erro
// The minimum HTTP response without header is 16 bytes:
// "HTTP/X.X" SP 3DIGITS CRLF CRLF
if len(raw) < 16 {
- return nil, raw, fmt.Errorf("http: invalid response header length")
+ return nil, raw, errors.New(`http: invalid response header length`)
}
// The HTTP-name is case sensitive: "HTTP".
if !bytes.Equal(raw[:4], []byte("HTTP")) {
@@ -36,7 +37,7 @@ func ParseResponseHeader(raw []byte) (resp *http.Response, rest []byte, err erro
}
ilf := bytes.Index(raw, []byte{'\n'})
if ilf < 0 || raw[ilf-1] != '\r' {
- return nil, raw, fmt.Errorf("http: missing CRLF on status line")
+ return nil, raw, errors.New(`http: missing CRLF on status line`)
}
resp = &http.Response{
@@ -55,7 +56,7 @@ func ParseResponseHeader(raw []byte) (resp *http.Response, rest []byte, err erro
resp.StatusCode, err = strconv.Atoi(string(raw[9:12]))
if err != nil {
- return nil, raw, fmt.Errorf("http: status code: " + err.Error())
+ return nil, raw, fmt.Errorf(`http: status code: %w`, err)
}
if resp.StatusCode < 100 || resp.StatusCode >= 600 {
return nil, raw, fmt.Errorf("http: invalid status code '%s'", raw[9:12])
@@ -87,7 +88,7 @@ func parseHeaders(raw []byte) (header http.Header, rest []byte, err error) {
for len(rest) > 0 {
switch len(rest) {
case 1:
- return nil, rest, fmt.Errorf(`http: missing CRLF at the end`)
+ return nil, rest, errors.New(`http: missing CRLF at the end`)
default:
if rest[0] == '\r' && rest[1] == '\n' {
rest = rest[2:]
@@ -105,10 +106,10 @@ func parseHeaders(raw []byte) (header http.Header, rest []byte, err error) {
tok, c = parser.Read()
if c != '\n' {
- return nil, nil, fmt.Errorf(`http: missing CRLF at the end of field line`)
+ return nil, nil, errors.New(`http: missing CRLF at the end of field line`)
}
if tok[len(tok)-1] != '\r' {
- return nil, nil, fmt.Errorf(`http: missing CR at the end of line`)
+ return nil, nil, errors.New(`http: missing CR at the end of line`)
}
tok = bytes.TrimSpace(tok)
diff --git a/lib/http/response_test.go b/lib/http/response_test.go
index bd9ccbd8..5f1c55bf 100644
--- a/lib/http/response_test.go
+++ b/lib/http/response_test.go
@@ -103,7 +103,7 @@ func TestParseResponseHeader(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- got, rest, err := ParseResponseHeader([]byte(c.raw))
+ got, rest, err := ParseResponseHeader([]byte(c.raw)) //nolint: bodyclose
if err != nil {
test.Assert(t, "error", c.expErr, err.Error())
continue
diff --git a/lib/http/server.go b/lib/http/server.go
index 4d9a627f..a1695a36 100644
--- a/lib/http/server.go
+++ b/lib/http/server.go
@@ -100,12 +100,12 @@ func (srv *Server) RegisterEndpoint(ep *Endpoint) (err error) {
return nil
}
if ep.Call == nil {
- return fmt.Errorf("http.RegisterEndpoint: empty Call field")
+ return errors.New(`http.RegisterEndpoint: empty Call field`)
}
switch ep.Method {
case RequestMethodConnect:
- return fmt.Errorf("http.RegisterEndpoint: can't handle CONNECT method yet")
+ return errors.New(`http.RegisterEndpoint: can't handle CONNECT method yet`)
case RequestMethodDelete:
err = srv.registerDelete(ep)
case RequestMethodHead:
@@ -119,7 +119,7 @@ func (srv *Server) RegisterEndpoint(ep *Endpoint) (err error) {
case RequestMethodPut:
err = srv.registerPut(ep)
case RequestMethodTrace:
- return fmt.Errorf("http.RegisterEndpoint: can't handle TRACE method yet")
+ return errors.New(`http.RegisterEndpoint: can't handle TRACE method yet`)
default:
ep.Method = RequestMethodGet
err = srv.registerGet(ep)
diff --git a/lib/http/server_test.go b/lib/http/server_test.go
index 4d573540..eee0144c 100644
--- a/lib/http/server_test.go
+++ b/lib/http/server_test.go
@@ -6,8 +6,8 @@ package http
import (
"bytes"
+ "context"
"errors"
- "fmt"
"io"
"log"
"mime"
@@ -136,7 +136,7 @@ func TestRegisterDelete(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- err := testServer.RegisterEndpoint(c.ep)
+ var err = testServer.RegisterEndpoint(c.ep)
if err != nil {
if !errors.Is(ErrEndpointAmbiguous, err) {
test.Assert(t, "error", c.expError, err.Error())
@@ -148,9 +148,14 @@ func TestRegisterDelete(t *testing.T) {
continue
}
- req, e := http.NewRequest(http.MethodDelete, c.reqURL, nil)
- if e != nil {
- t.Fatal(e)
+ var (
+ ctx = context.Background()
+ req *http.Request
+ )
+
+ req, err = http.NewRequestWithContext(ctx, http.MethodDelete, c.reqURL, nil)
+ if err != nil {
+ t.Fatal(err)
}
res, e := client.Do(req)
@@ -228,9 +233,15 @@ func TestRegisterEvaluator(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- req, e := http.NewRequest(http.MethodDelete, c.reqURL, nil)
- if e != nil {
- t.Fatal(e)
+ var (
+ ctx = context.Background()
+ req *http.Request
+ err error
+ )
+
+ req, err = http.NewRequestWithContext(ctx, http.MethodDelete, c.reqURL, nil)
+ if err != nil {
+ t.Fatal(err)
}
res, e := client.Do(req)
@@ -298,9 +309,15 @@ func TestRegisterGet(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- req, e := http.NewRequest(http.MethodGet, c.reqURL, nil)
- if e != nil {
- t.Fatal(e)
+ var (
+ ctx = context.Background()
+ req *http.Request
+ err error
+ )
+
+ req, err = http.NewRequestWithContext(ctx, http.MethodGet, c.reqURL, nil)
+ if err != nil {
+ t.Fatal(err)
}
res, e := client.Do(req)
@@ -365,9 +382,15 @@ func TestRegisterHead(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- req, e := http.NewRequest(http.MethodHead, c.reqURL, nil)
- if e != nil {
- t.Fatal(e)
+ var (
+ ctx = context.Background()
+ req *http.Request
+ err error
+ )
+
+ req, err = http.NewRequestWithContext(ctx, http.MethodHead, c.reqURL, nil)
+ if err != nil {
+ t.Fatal(err)
}
res, e := client.Do(req)
@@ -431,7 +454,9 @@ func TestRegisterPatch(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- req, e := http.NewRequest(http.MethodPatch, c.reqURL, nil)
+ var ctx = context.Background()
+
+ req, e := http.NewRequestWithContext(ctx, http.MethodPatch, c.reqURL, nil)
if e != nil {
t.Fatal(e)
}
@@ -503,7 +528,9 @@ k=vv`,
var buf bytes.Buffer
_, _ = buf.WriteString(c.reqBody)
- req, e := http.NewRequest(http.MethodPost, c.reqURL, &buf)
+ var ctx = context.Background()
+
+ req, e := http.NewRequestWithContext(ctx, http.MethodPost, c.reqURL, &buf)
if e != nil {
t.Fatal(e)
}
@@ -566,7 +593,9 @@ func TestRegisterPut(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- req, e := http.NewRequest(http.MethodPut, c.reqURL, nil)
+ var ctx = context.Background()
+
+ req, e := http.NewRequestWithContext(ctx, http.MethodPut, c.reqURL, nil)
if e != nil {
t.Fatal(e)
}
@@ -643,7 +672,9 @@ func TestServeHTTPOptions(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- req, err := http.NewRequest(http.MethodOptions, c.reqURL, nil)
+ var ctx = context.Background()
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodOptions, c.reqURL, nil)
if err != nil {
t.Fatal(err)
}
@@ -652,6 +683,7 @@ func TestServeHTTPOptions(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ _ = res.Body.Close()
gotAllow := res.Header.Get("Allow")
@@ -672,7 +704,7 @@ func TestStatusError(t *testing.T) {
return nil, liberrors.Internal(nil)
}
cbCustomErr = func(_ *EndpointRequest) ([]byte, error) {
- return nil, fmt.Errorf("Custom error")
+ return nil, errors.New(`Custom error`)
}
err error
@@ -796,7 +828,9 @@ func TestStatusError(t *testing.T) {
for _, c := range cases {
t.Log(c.desc)
- req, e := http.NewRequest(http.MethodPost, c.reqURL, nil)
+ var ctx = context.Background()
+
+ req, e := http.NewRequestWithContext(ctx, http.MethodPost, c.reqURL, nil)
if e != nil {
t.Fatal(e)
}
@@ -882,7 +916,9 @@ func TestServer_Options_HandleFS(t *testing.T) {
}}
for _, c = range cases {
- req, err = http.NewRequest(http.MethodGet, testServerURL+c.reqPath, nil)
+ var ctx = context.Background()
+
+ req, err = http.NewRequestWithContext(ctx, http.MethodGet, testServerURL+c.reqPath, nil)
if err != nil {
t.Fatalf("%s: %s", c.desc, err)
}
@@ -902,6 +938,10 @@ func TestServer_Options_HandleFS(t *testing.T) {
if err != nil {
t.Fatalf("%s: %s", c.desc, err)
}
+ err = res.Body.Close()
+ if err != nil {
+ t.Fatalf("%s: %s", c.desc, err)
+ }
test.Assert(t, "response body", c.expResBody, string(gotBody))
}
@@ -937,7 +977,7 @@ func TestServer_handleRange(t *testing.T) {
header.Set(HeaderRange, string(headerRange))
- httpRes, resBody, err = cl.Get(`/index.html`, header, nil)
+ httpRes, resBody, err = cl.Get(`/index.html`, header, nil) //nolint: bodyclose
if err != nil {
t.Fatal(err)
}
@@ -999,9 +1039,24 @@ func TestServer_handleRange_HEAD(t *testing.T) {
t.Fatal(err)
}
+ var (
+ ctx = context.Background()
+ url = testServerURL + `/index.html`
+ httpReq *http.Request
+ )
+
+ httpReq, err = http.NewRequestWithContext(ctx, http.MethodHead, url, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
var httpRes *http.Response
- httpRes, err = cl.Client.Head(testServerURL + `/index.html`)
+ httpRes, err = cl.Client.Do(httpReq)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = httpRes.Body.Close()
if err != nil {
t.Fatal(err)
}
@@ -1090,7 +1145,7 @@ func TestServerHandleRangeBig(t *testing.T) {
resBody []byte
)
- httpRes, resBody, err = cl.Head(pathBig, nil, nil)
+ httpRes, resBody, err = cl.Head(pathBig, nil, nil) //nolint: bodyclose
if err != nil {
t.Fatal(err)
}
@@ -1106,7 +1161,7 @@ func TestServerHandleRangeBig(t *testing.T) {
headers.Set(HeaderRange, `bytes=0-`)
- httpRes, resBody, err = cl.Get(pathBig, headers, nil)
+ httpRes, resBody, err = cl.Get(pathBig, headers, nil) //nolint: bodyclose
if err != nil {
t.Fatal(err)
}
diff --git a/lib/http/sseclient/sseclient.go b/lib/http/sseclient/sseclient.go
index 04cd1bbf..a9004005 100644
--- a/lib/http/sseclient/sseclient.go
+++ b/lib/http/sseclient/sseclient.go
@@ -227,7 +227,7 @@ func (cl *Client) handshake() (packet []byte, err error) {
var httpRes *http.Response
- httpRes, packet, err = libhttp.ParseResponseHeader(packet)
+ httpRes, packet, err = libhttp.ParseResponseHeader(packet) //nolint: bodyclose
if err != nil {
return nil, err
}