github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/libkb/httputil.go (about)

     1  package libkb
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  )
     8  
     9  func discardAndClose(rc io.ReadCloser) error {
    10  	_, _ = io.Copy(io.Discard, rc)
    11  	return rc.Close()
    12  }
    13  
    14  // DiscardAndCloseBody reads as much as possible from the body of the
    15  // given response, and then closes it.
    16  //
    17  // This is because, in order to free up the current connection for
    18  // re-use, a response body must be read from before being closed; see
    19  // http://stackoverflow.com/a/17953506 .
    20  //
    21  // Instead of doing:
    22  //
    23  //	res, _ := ...
    24  //	defer res.Body.Close()
    25  //
    26  // do
    27  //
    28  //	res, _ := ...
    29  //	defer DiscardAndCloseBody(res)
    30  //
    31  // instead.
    32  func DiscardAndCloseBody(resp *http.Response) error {
    33  	if resp == nil {
    34  		return fmt.Errorf("Nothing to discard (http.Response was nil)")
    35  	}
    36  	return discardAndClose(resp.Body)
    37  }