Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading