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