Search code examples
gogo-http

Do I need to close Response body of http request even if I don't read it?


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()?


Solution

  • 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.