Skip to content

Commit 246e4c5

Browse files
itsksaurabhKumar Saurabh
authored and
Kumar Saurabh
committed
Ensure the response body is fully read and closed before we reconnect to reuse the same underlying TCP connection - @itsksaurabh
1 parent e881974 commit 246e4c5

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

github/github.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,23 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Res
554554

555555
return nil, err
556556
}
557-
defer resp.Body.Close()
557+
558+
defer func() {
559+
// Ensure the response body is fully read and closed
560+
// before we reconnect, so that we reuse the same TCP connection.
561+
// Close the previous response's body. But read at least some of
562+
// the body so if it's small the underlying TCP connection will be
563+
// re-used. No need to check for errors: if it fails, the Transport
564+
// won't reuse it anyway.
565+
const maxBodySlurpSize = 2 << 10
566+
if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
567+
io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
568+
}
569+
570+
if rerr := resp.Body.Close(); err == nil {
571+
err = rerr
572+
}
573+
}()
558574

559575
response := newResponse(resp)
560576

0 commit comments

Comments
 (0)