From da2cc385dbfd887a5476317df538a41508aad0a2 Mon Sep 17 00:00:00 2001 From: Volodymyr Dorokhov Date: Thu, 28 Jan 2021 11:12:14 +0000 Subject: [PATCH] Fix body nil checking in NewRequest NewRequest accepts interface{} as body argument but doesn't check it on nil properly. It should check that not only variable is nil, but also pointer value is nil. Otherwise it constructs different Request objects for the same parameters. Tests are added. --- client.go | 9 +++++++++ client_test.go | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/client.go b/client.go index 79dc931..4332060 100644 --- a/client.go +++ b/client.go @@ -34,6 +34,7 @@ import ( "net/http" "net/url" "os" + "reflect" "regexp" "strconv" "strings" @@ -154,6 +155,10 @@ func getBodyReaderAndContentLength(rawBody interface{}) (ReaderFunc, int64, erro var bodyReader ReaderFunc var contentLength int64 + if isNil(rawBody) { + return bodyReader, contentLength, nil + } + switch body := rawBody.(type) { // If they gave us a function already, great! Use it. case ReaderFunc: @@ -772,3 +777,7 @@ func (c *Client) StandardClient() *http.Client { Transport: &RoundTripper{Client: c}, } } + +func isNil(v interface{}) bool { + return v == nil || ((reflect.ValueOf(v).Kind() == reflect.Ptr || reflect.ValueOf(v).Kind() == reflect.Slice) && reflect.ValueOf(v).IsNil()) +} diff --git a/client_test.go b/client_test.go index b8a3d9d..df63726 100644 --- a/client_test.go +++ b/client_test.go @@ -842,3 +842,21 @@ func TestClient_StandardClient(t *testing.T) { t.Fatalf("expected %v, got %v", client, v) } } + +func Test_NewRequest(t *testing.T) { + req, err := NewRequest("GET", "localhost:1234", nil) + if err != nil { + t.Fatalf("failed to create a request: %s", err) + } + + var b []byte + b = nil + r, err := NewRequest("GET", "localhost:1234", b) + if err != nil { + t.Fatalf("failed to create a request: %s", err) + } + + if req.body != nil || r.body != nil { + t.Fatalf("expected nil body for both requests, got:%v %v", req.body, r.body) + } +}