1

I have the following code:

resp, err = http.Head("http:something.com")
if err != nil {
    //do something
}

if resp.StatusCode == http.StatusOK {
    // do something     
}

As I am not reading the body of the resp I am assuming that I don't need to close it like resp.Body.Close(). Am I right in my assumption or should I still call resp.Body.Close()?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
unitSphere
  • 241
  • 3
  • 17
  • 3
    You should close the body regardless of whether or not you're reading it. – mkopriva Jan 06 '22 at 07:38
  • 1
    Do you think it hurts to close the body? The documentation states "It is the caller's responsibility to close Body." Do you think this doesn't apply in your case? How do you justify your assumption that you do not need to close the body just because you do not read it? – Volker Jan 06 '22 at 07:38
  • 4
    The rule of thumb when working with Go standard library (and 3rd-party code which follows the same—good—design) is to `Close` anything which your code deals with: this is simply because Go's types cannot have destructors and implement explicit methods to free resources other than memory held by instances of such types. In your particular case a failure to close the response's body may (and usually will) either prevent proper reusing of the underlying TCP connection or will result in not closing it which is a resource leak and may lead to resource exhaustion on the client side. – kostix Jan 06 '22 at 08:47
  • 1
    [More on Go not having destructors](https://stackoverflow.com/a/32781054/720999). – kostix Jan 06 '22 at 08:48

1 Answers1

6

http.Head() is a wrapper around DefaultClient.Head() which issues Client.Do() which documents that:

If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.

This should be enough for you to close it.

Even though you're using HTTP HEAD method, this is just more of a "recommendation" to the server. A server that does not conform to RFC may return a body even if it shouldn't (for a HEAD request), and Go's net/http library may provide that body via Response.Body. So you should close it. Even if no body is sent or presented to you, closing it will do no harm.

rustyx
  • 80,671
  • 25
  • 200
  • 267
icza
  • 389,944
  • 63
  • 907
  • 827