From 39cfb7609d293ae9acc40d09645d01258dc8edbf Mon Sep 17 00:00:00 2001 From: Luke Young Date: Sun, 20 Oct 2019 06:03:55 +0000 Subject: [PATCH] net/http: make Transport.roundTrip close body on invalid method Updates #35015 Change-Id: Ibfe8f72ed3887ca88ce9c1d8a29dacda72f3fe17 GitHub-Last-Rev: 4bfc56e71660ad9624ac5eb594b3afd0d221c99d GitHub-Pull-Request: golang/go#35014 Reviewed-on: https://go-review.googlesource.com/c/go/+/202237 Reviewed-by: Emmanuel Odeke Run-TryBot: Emmanuel Odeke TryBot-Result: Gobot Gobot --- src/net/http/transport.go | 1 + src/net/http/transport_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/net/http/transport.go b/src/net/http/transport.go index af48eaa9f0..bd9717ea15 100644 --- a/src/net/http/transport.go +++ b/src/net/http/transport.go @@ -492,6 +492,7 @@ func (t *Transport) roundTrip(req *Request) (*Response, error) { return nil, &badStringError{"unsupported protocol scheme", scheme} } if req.Method != "" && !validMethod(req.Method) { + req.closeBody() return nil, fmt.Errorf("net/http: invalid method %q", req.Method) } if req.URL.Host == "" { diff --git a/src/net/http/transport_test.go b/src/net/http/transport_test.go index d7eef0d94c..0fe1283d97 100644 --- a/src/net/http/transport_test.go +++ b/src/net/http/transport_test.go @@ -5719,3 +5719,32 @@ func TestInvalidHeaderResponse(t *testing.T) { t.Errorf(`bad "Foo " header value: %q, want %q`, v, "bar") } } + +type bodyCloser bool + +func (bc *bodyCloser) Close() error { + *bc = true + return nil +} +func (bc *bodyCloser) Read(b []byte) (n int, err error) { + return 0, io.EOF +} + +func TestInvalidMethodClosesBody(t *testing.T) { + cst := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) + defer cst.Close() + var bc bodyCloser + u, _ := url.Parse(cst.URL) + req := &Request{ + Method: " ", + URL: u, + Body: &bc, + } + _, err := DefaultClient.Do(req) + if err == nil { + t.Fatal("Expected an error") + } + if !bc { + t.Fatal("Expected body to have been closed") + } +} -- 2.51.0