Skip to content

Commit e19d4dd

Browse files
authored
Read response body for TCP connection reuse (#1576)
1 parent 512c583 commit e19d4dd

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

github/github.go

+15-1
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,21 @@ 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+
resp.Body.Close()
571+
}()
558572

559573
response := newResponse(resp)
560574

0 commit comments

Comments
 (0)