From eb2a40b4d49d9075ed1e98f4a76cfd5697a34e26 Mon Sep 17 00:00:00 2001 From: Will Norris Date: Tue, 14 Oct 2014 18:09:24 -0700 Subject: [PATCH] pass nil to http.NewRequest if body is nil --- github/github.go | 3 ++- github/github_test.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/github/github.go b/github/github.go index c9236e2..7237027 100644 --- a/github/github.go +++ b/github/github.go @@ -151,8 +151,9 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Requ u := c.BaseURL.ResolveReference(rel) - buf := new(bytes.Buffer) + var buf io.ReadWriter if body != nil { + buf = new(bytes.Buffer) err := json.NewEncoder(buf).Encode(body) if err != nil { return nil, err diff --git a/github/github_test.go b/github/github_test.go index 5fc347c..670186a 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -225,6 +225,23 @@ func TestNewRequest_emptyUserAgent(t *testing.T) { } } +// If a nil body is passed to github.NewRequest, make sure that nil is also +// passed to http.NewRequest. In most cases, passing in io.Reader the returns +// no content is fine, since there is no difference between an HTTP request +// body that is an empty string versus one that is not set at all. However in +// certain cases, intermediate systems may treat these differently resulting in +// subtle errors. +func TestNewRequest_emptyBody(t *testing.T) { + c := NewClient(nil) + req, err := c.NewRequest("GET", "/", nil) + if err != nil { + t.Fatalf("NewRequest returned unexpected error: %v", err) + } + if req.Body != nil { + t.Fatalf("constructed request contains a non-nil Body") + } +} + func TestResponse_populatePageValues(t *testing.T) { r := http.Response{ Header: http.Header{