@@ -722,7 +722,7 @@ func (t *Transport) roundTrip(req *Request) (_ *Response, err error) {
722
722
if e , ok := err .(transportReadFromServerError ); ok {
723
723
err = e .err
724
724
}
725
- if b , ok := req .Body .(* readTrackingBody ); ok && ! b .didClose {
725
+ if b , ok := req .Body .(* readTrackingBody ); ok && ! b .didClose . Load () {
726
726
// Issue 49621: Close the request body if pconn.roundTrip
727
727
// didn't do so already. This can happen if the pconn
728
728
// write loop exits without reading the write request.
@@ -752,8 +752,8 @@ var errCannotRewind = errors.New("net/http: cannot rewind body after connection
752
752
753
753
type readTrackingBody struct {
754
754
io.ReadCloser
755
- didRead bool
756
- didClose bool
755
+ didRead bool // not atomic.Bool because only one goroutine (the user's) should be accessing
756
+ didClose atomic. Bool
757
757
}
758
758
759
759
func (r * readTrackingBody ) Read (data []byte ) (int , error ) {
@@ -762,7 +762,9 @@ func (r *readTrackingBody) Read(data []byte) (int, error) {
762
762
}
763
763
764
764
func (r * readTrackingBody ) Close () error {
765
- r .didClose = true
765
+ if ! r .didClose .CompareAndSwap (false , true ) {
766
+ return nil
767
+ }
766
768
return r .ReadCloser .Close ()
767
769
}
768
770
@@ -784,10 +786,10 @@ func setupRewindBody(req *Request) *Request {
784
786
// rewindBody takes care of closing req.Body when appropriate
785
787
// (in all cases except when rewindBody returns req unmodified).
786
788
func rewindBody (req * Request ) (rewound * Request , err error ) {
787
- if req .Body == nil || req .Body == NoBody || (! req .Body .(* readTrackingBody ).didRead && ! req .Body .(* readTrackingBody ).didClose ) {
789
+ if req .Body == nil || req .Body == NoBody || (! req .Body .(* readTrackingBody ).didRead && ! req .Body .(* readTrackingBody ).didClose . Load () ) {
788
790
return req , nil // nothing to rewind
789
791
}
790
- if ! req .Body .(* readTrackingBody ).didClose {
792
+ if ! req .Body .(* readTrackingBody ).didClose . Load () {
791
793
req .closeBody ()
792
794
}
793
795
if req .GetBody == nil {
0 commit comments