FAQ

On Mon, Aug 24, 2015 at 12:48 PM, wrote:

Is it considered a best practice to always add the following after
http.DefaultClient.Do returns a non-error response?

defer res.Body.Close()
defer io.Copy(ioutil.Discard, res.Body)

That way subsequent code in the function can read the body however it sees
fit, but if it doesn't read it to completion for some reason, we cleanup
and make sure the connection can be re-used. And it's a no-op if the body
was already read fully.
defer'ing the Body.Close is definitely a best practice.

You can add the io.Copy call if it suits your code, though I can't think of
many cases where I didn't know if I would read the Body or not. While not
exactly a noop, I don't think it ever really hurts to add it when you might
need it, since ioutil.Discard gets its copy buffer from a sync.Pool.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 8 of 11 | next ›
Discussion Overview
groupgolang-nuts @
categoriesgo
postedDec 10, '14 at 1:46p
activeAug 24, '15 at 6:41p
posts11
users4
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase