FAQ
Thanks. There are 3 common cases I've encountered where the io.Copy is
needed:
- Reading the body using json.Decoder - it can stop without reading the
entire body contents
- Early return without reading the body b/c of a non-200 response
- Client code doing a POST where it checks the http response code without
reading the body

Deferring the io.Copy at the same spot as the Close lets me ensure the body
is always read without having to manually review each error case
On Monday, August 24, 2015 at 10:04:53 AM UTC-7, James Bardin wrote:

On Mon, Aug 24, 2015 at 12:48 PM, <cbro...@gmail.com <javascript:>> 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 | 9 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