Skip to content

Commit 450f3f6

Browse files
seankhliaogopherbot
authored andcommitted
net/http/httptest: match net/http ContentLength behavior for http.NoBody
Fixes #68476 Change-Id: I05122e5ec5e6b290eec93f3db444fcf1de19c030 Reviewed-on: https://go-review.googlesource.com/c/go/+/599815 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Damien Neil <[email protected]> Reviewed-by: Dmitri Shuralyov <[email protected]> Auto-Submit: Daniel Martí <[email protected]>
1 parent dcbdc1a commit 450f3f6

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

src/net/http/httptest/httptest.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ func NewRequest(method, target string, body io.Reader) *http.Request {
3434
//
3535
// An empty method means "GET".
3636
//
37-
// The provided body may be nil. If the body is of type *bytes.Reader,
38-
// *strings.Reader, or *bytes.Buffer, the Request.ContentLength is
39-
// set.
37+
// The provided body may be nil. If the body is of type [bytes.Reader],
38+
// [strings.Reader], [bytes.Buffer], or the value [http.NoBody],
39+
// the Request.ContentLength is set.
4040
//
4141
// NewRequest panics on error for ease of use in testing, where a
4242
// panic is acceptable.
@@ -69,6 +69,9 @@ func NewRequestWithContext(ctx context.Context, method, target string, body io.R
6969
default:
7070
req.ContentLength = -1
7171
}
72+
if body == http.NoBody {
73+
req.ContentLength = 0
74+
}
7275
if rc, ok := body.(io.ReadCloser); ok {
7376
req.Body = rc
7477
} else {

src/net/http/httptest/httptest_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,24 @@ func TestNewRequestWithContext(t *testing.T) {
156156
wantBody: "foo",
157157
},
158158

159+
{
160+
name: "Post with NoBody",
161+
method: "POST",
162+
uri: "/",
163+
body: http.NoBody,
164+
want: &http.Request{
165+
Method: "POST",
166+
Host: "example.com",
167+
URL: &url.URL{Path: "/"},
168+
Header: http.Header{},
169+
Proto: "HTTP/1.1",
170+
ProtoMajor: 1,
171+
ProtoMinor: 1,
172+
RemoteAddr: "192.0.2.1:1234",
173+
RequestURI: "/",
174+
},
175+
},
176+
159177
{
160178
name: "OPTIONS *",
161179
method: "OPTIONS",

0 commit comments

Comments
 (0)