net/http: clarify documentation around when or if it is safe to reuse a request body #26409
Labels
Documentation
Issues describing a change to documentation.
FrozenDueToAge
NeedsInvestigation
Someone must examine and confirm this is a valid issue and not a duplicate of an existing one.
Milestone
The net/http library's
Request
documents that a client'sTransport
is responsible for calling a request body'sClose
method.A response can be returned before a request's body is entirely written. I looked a bit and there appears to be no guarantee about a request body being closed at any time (even after a response body hits
io.EOF
and is closed).To ensure that a request body is safe to reuse, we have to wrap it in a type that tracks an outstanding close.
However, if a body passed to NewRequest is one of a few types,
bytes.Reader
being one of those types, a request automatically has its GetBody field populated. On redirect, if any of the body has been read, the body is "cloned" and the original body is closed. If I want to wrap abytes.Reader
in this close counter, I lose the ability to haveGetBody
used on redirects. My alternative is to setGetBody
myself. That makes this close counter a bit more difficult.I know that
GetBody
is not called after we have a response since there will be no more redirects to follow. So, being careful, I can write a close counter that increments the number of expected closes if I setGetBody
appropriately and it is called.I currently have the following code:
and it can be used somehow like the following:
I've gathered most of this by reading a bit of the net/http source, but it would be great to have documentation guidance for when exactly it is safe to reuse a request body and if it is safe at all to reuse a request body with
GetBody
.The text was updated successfully, but these errors were encountered: