Skip to content

Commit 2ef1965

Browse files
authored
fix: improve connection closing (#156)
1 parent 0e2a931 commit 2ef1965

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

mongodbatlas/mongodbatlas.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -391,9 +391,18 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Res
391391
}
392392

393393
defer func() {
394-
if rerr := resp.Body.Close(); err == nil {
395-
err = rerr
394+
// Ensure the response body is fully read and closed
395+
// before we reconnect, so that we reuse the same TCP connection.
396+
// Close the previous response's body. But read at least some of
397+
// the body so if it's small the underlying TCP connection will be
398+
// re-used. No need to check for errors: if it fails, the Transport
399+
// won't reuse it anyway.
400+
const maxBodySlurpSize = 2 << 10
401+
if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
402+
_, _ = io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
396403
}
404+
405+
resp.Body.Close()
397406
}()
398407

399408
response := &Response{Response: resp}

0 commit comments

Comments
 (0)