When not to close response body

golang requires the response body of an http request be closed in user code, to free resources:

client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
    return nil, err
defer resp.Body.Close()

My question is: why is this the design? Are there situations where not closing is beneficial? Why does the standard library not close the connection within client.Do(req) for the user?

I ask because this is a gotcha I see fairly frequently reviewing code.

>Solution :

There is no size limit to the content you receive from the server. You may be downloading a very large file. That’s why the response contains a reader: so you can stream the response.

Since you can stream the response, you have to close the stream when you are done, or when you are not interested in the rest of the results. When you close the stream, the server will know that you are no longer interested in receiving the rest of the stream, and it will have a chance to clean up.

Leave a Reply