Open jfrancisco0 opened 1 month ago
Related Issues and Documentation
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
As you already see, httptest.NewRequest
is documented as
The provided body may be nil. If the body is of type bytes.Reader, strings.Reader, or *bytes.Buffer, the Request.ContentLength is set.
So it is clearly fine to pass a nil
body. There is no need to change it.
Also, as http.NoBody
is not any of those types, the ContentLength is "unset", which matches the documentation. Maybe we want to explicitly document it set to -1?
cc @neild
Change https://go.dev/cl/599815 mentions this issue: net/http/httptest: match net/http ContentLength behavior for http.NoBody
Go version
go version go1.22.5 darwin/arm64
Output of
go env
in your module/workspace:What did you do?
The
gocritic
linter suggests I should usehttp.NoBody
instead ofnil
for empty body requests. However,httptest.NewRequest()
shows different behaviour whenhttp.NoBody
is sent vs whennil
is sent. Note that this is only the case for the httptest package, ashttp.NewRequest()
- from the http package - works as expected.See the example from https://go.dev/play/p/n9UxgUsAfM8
What did you see happen?
Creating a request with a
http.NoBody
body results in aContentLength
value of-1
instead of the expected0
you would get with anil
body.set ContentLength as
0
, butsets ContentLength as
-1
.This makes my tests fail, as the server returns an error. According to the documentation,
ContentLength: -1
means unknown, which should not be the case forhttp.NoBody
, as that's and empty body (length 0). This happens becausehttp.NoBody
is aio.ReadCloser
, which doesn't match any of the types in the switch.What did you expect to see?
The request with a
http.NoBody
body should haveContentLength: 0
.The
http
package never sets a negativeContentLength
for backwards compatibility (source).I suggest that either the same logic is ported over to the
httptest
package, or thathttp.NoBody
is accounted for as an exception, like it was in thehttp
package before the reversal in this commit.