FAQ
Hi

Wanted to gain better understanding of this. The recommendation I see about
closing http response body always comes with a "defer". I wanted to
understand if it's required to defer closing http response body always or
is it alright if it's closed once you are done with it, for example,
body, err := ioutil.ReadAll(res.Body)
if err!= nil{
    //handle error
    //return
}
res.Body.Close()

Why is a 'defer'ed closure recommended always?

Thank you
Neelesh

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

  • Andy Balholm at May 11, 2016 at 2:04 am
    It is a pretty common practice to do defer x.Close() with all kinds of resources, to ensure that they get closed even if there is an early return from the function for an error. (Though it is not a good idea when x is a file that is being written to, since it ignores any errors returned by Close.) But it is not obligatory.

    Andy

    --
    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.
  • Sean Russell at May 11, 2016 at 10:50 am
    It is not necessary. defer provides locality of operations, so you can put the open and close close together, improving changes that you won't later forget to perform the clean-up operation.

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

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedMay 11, '16 at 12:27a
activeMay 11, '16 at 10:50a
posts3
users3
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase