]> Cypherpunks repositories - gostls13.git/commitdiff
net/http/httptest: match net/http ContentLength behavior for http.NoBody
authorSean Liao <sean@liao.dev>
Fri, 19 Jul 2024 22:28:54 +0000 (23:28 +0100)
committerGopher Robot <gobot@golang.org>
Tue, 11 Feb 2025 16:49:01 +0000 (08:49 -0800)
Fixes #68476

Change-Id: I05122e5ec5e6b290eec93f3db444fcf1de19c030
Reviewed-on: https://go-review.googlesource.com/c/go/+/599815
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
Auto-Submit: Daniel Martí <mvdan@mvdan.cc>

src/net/http/httptest/httptest.go
src/net/http/httptest/httptest_test.go

index 0c0dbb40e89bc567a6b4bcac34f7622c4339284d..7fe7107a9a191c13076967ab934d7f72cd0c7043 100644 (file)
@@ -34,9 +34,9 @@ func NewRequest(method, target string, body io.Reader) *http.Request {
 //
 // An empty method means "GET".
 //
-// The provided body may be nil. If the body is of type *bytes.Reader,
-// *strings.Reader, or *bytes.Buffer, the Request.ContentLength is
-// set.
+// The provided body may be nil. If the body is of type [bytes.Reader],
+// [strings.Reader], [bytes.Buffer], or the value [http.NoBody],
+// the Request.ContentLength is set.
 //
 // NewRequest panics on error for ease of use in testing, where a
 // panic is acceptable.
@@ -69,6 +69,9 @@ func NewRequestWithContext(ctx context.Context, method, target string, body io.R
                default:
                        req.ContentLength = -1
                }
+               if body == http.NoBody {
+                       req.ContentLength = 0
+               }
                if rc, ok := body.(io.ReadCloser); ok {
                        req.Body = rc
                } else {
index d5a4c3dc9d19a10b2a368f96f25d76f532a405f4..5f2215cfc6cdc1815a91438226236447eb737c7d 100644 (file)
@@ -156,6 +156,24 @@ func TestNewRequestWithContext(t *testing.T) {
                        wantBody: "foo",
                },
 
+               {
+                       name:   "Post with NoBody",
+                       method: "POST",
+                       uri:    "/",
+                       body:   http.NoBody,
+                       want: &http.Request{
+                               Method:     "POST",
+                               Host:       "example.com",
+                               URL:        &url.URL{Path: "/"},
+                               Header:     http.Header{},
+                               Proto:      "HTTP/1.1",
+                               ProtoMajor: 1,
+                               ProtoMinor: 1,
+                               RemoteAddr: "192.0.2.1:1234",
+                               RequestURI: "/",
+                       },
+               },
+
                {
                        name:   "OPTIONS *",
                        method: "OPTIONS",