net/http/httptest: wrong ContentLength for request with http.NoBody #68476
Labels
FixPending
Issues that have a fix which has not yet been reviewed or submitted.
NeedsFix
The path to resolution is known, but the work has not been done.
Milestone
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.The text was updated successfully, but these errors were encountered: