Closing http response

Good day,

I just want to ask.
Do I still need to close http response body, if I am just interested on its statuscode and the cookie?


Yes, it releases connection.

For a simple application it doesn’t matter but for heavy infra based apps and heavy load. YES

Thanks for the replies

But before deferring please do check if body is empty. If the body would be empty it would panic. :slight_smile:

As far as I know, closing an empty body of a succesful request doesn’t error (not sure about this one, not even sure if we mean the same by empty body), but even if it did, deferring the Close() will make you miss the error (unless you are returning a named error on an enclosing function an assign it), not panic. Am I missing somehting there?

So far on my initial test, closing it without reading still works, even on an empty or zero-length (hmm how should we call them) body.

Just to add a bit of information, the docs for http client state this for a Get, Post and PostForm:

// When err is nil, resp always contains a non-nil resp.Body.
// Caller should close resp.Body when done reading from it.

But, later on they say this about Do(), which is called in all of the above:

// On error, any Response can be ignored. A non-nil Response with a
// non-nil error only occurs when CheckRedirect fails, and even then
// the returned Response.Body is already closed.

So you should be fine deferring the body close after checking if the response errored, e.g…:

resp, err := http.Get("")
if err != nil {
    // Do something with your error, don't worry about the body
defer resp.Body.Close() // Defer closing the body when error is nil

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.