Skip to content

Commit 39cfb76

Browse files
bored-engineerodeke-em
authored andcommitted
net/http: make Transport.roundTrip close body on invalid method
Updates #35015 Change-Id: Ibfe8f72ed3887ca88ce9c1d8a29dacda72f3fe17 GitHub-Last-Rev: 4bfc56e GitHub-Pull-Request: #35014 Reviewed-on: https://go-review.googlesource.com/c/go/+/202237 Reviewed-by: Emmanuel Odeke <[email protected]> Run-TryBot: Emmanuel Odeke <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent 72275c0 commit 39cfb76

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/net/http/transport.go

+1
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,7 @@ func (t *Transport) roundTrip(req *Request) (*Response, error) {
492492
return nil, &badStringError{"unsupported protocol scheme", scheme}
493493
}
494494
if req.Method != "" && !validMethod(req.Method) {
495+
req.closeBody()
495496
return nil, fmt.Errorf("net/http: invalid method %q", req.Method)
496497
}
497498
if req.URL.Host == "" {

src/net/http/transport_test.go

+29
Original file line numberDiff line numberDiff line change
@@ -5719,3 +5719,32 @@ func TestInvalidHeaderResponse(t *testing.T) {
57195719
t.Errorf(`bad "Foo " header value: %q, want %q`, v, "bar")
57205720
}
57215721
}
5722+
5723+
type bodyCloser bool
5724+
5725+
func (bc *bodyCloser) Close() error {
5726+
*bc = true
5727+
return nil
5728+
}
5729+
func (bc *bodyCloser) Read(b []byte) (n int, err error) {
5730+
return 0, io.EOF
5731+
}
5732+
5733+
func TestInvalidMethodClosesBody(t *testing.T) {
5734+
cst := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
5735+
defer cst.Close()
5736+
var bc bodyCloser
5737+
u, _ := url.Parse(cst.URL)
5738+
req := &Request{
5739+
Method: " ",
5740+
URL: u,
5741+
Body: &bc,
5742+
}
5743+
_, err := DefaultClient.Do(req)
5744+
if err == nil {
5745+
t.Fatal("Expected an error")
5746+
}
5747+
if !bc {
5748+
t.Fatal("Expected body to have been closed")
5749+
}
5750+
}

0 commit comments

Comments
 (0)