Closing the Body of a http.Response with defer

782 views
Skip to first unread message

Andrew Chilton

unread,
Aug 19, 2011, 10:16:43 PM8/19/11
to golang-nuts
Hi everyone,

I'm currently hacking on some code which does the following:

r, err := http.DefaultClient.Do(&req)
if err != nil {
return nil, err
}

function_dowork_that_also_calls_r_body_close(r)

But I'm not really keen on the opening somewhere, closing somewhere
else thing. So I figured that this is exactly what defer is for, so
I'm going to try the following:

r, err := http.DefaultClient.Do(&req)
defer r.Body.Close()
if err != nil {
return nil, err
}

function_dowork(r)

Is this an acceptable use of defer and will it do what I expect it to?
I certainly like it a lot more than the previous version, but I just
want to check I'm not doing anything weird here.

Cheers,
Andy

--
Andrew Chilton
e: chi...@appsattic.com
w: http://www.appsattic.com/

Gustavo Niemeyer

unread,
Aug 19, 2011, 10:25:17 PM8/19/11
to Andrew Chilton, golang-nuts
> Is this an acceptable use of defer and will it do what I expect it to?
> I certainly like it a lot more than the previous version, but I just
> want to check I'm not doing anything weird here.

Yeah, as we discussed online, it's a good use for defer.

--
Gustavo Niemeyer
http://niemeyer.net
http://niemeyer.net/plus
http://niemeyer.net/twitter
http://niemeyer.net/blog

-- I never filed a patent.

Kyle Lemons

unread,
Aug 22, 2011, 11:42:14 AM8/22/11
to Gustavo Niemeyer, Andrew Chilton, golang-nuts
Shouldn't the defer be after the error check?  Other than that, I frequently use defer for that exact purpose.
~K

Andrew Chilton

unread,
Aug 22, 2011, 5:01:59 PM8/22/11
to Kyle Lemons, Gustavo Niemeyer, golang-nuts
On 23 August 2011 03:42, Kyle Lemons <kev...@google.com> wrote:
> Shouldn't the defer be after the error check?  Other than that, I frequently
> use defer for that exact purpose.

You're so right - thanks. :) I wrote a test program to just make sure:

* https://gist.github.com/1163510

Once compiled, an argument of 'http://www.chilts.org/' means that
http.Get() is fine but 'www.chilts.org' isn't (since I didn't provide
a protocol). The program works fine in both cases where the defer is
_after_ the error check.

If the defer is before the error check, it goes haywire with the
error: "panic: runtime error: invalid memory address or nil pointer
dereference".

Thanks Kyle and well spotted. :)

Reply all
Reply to author
Forward
0 new messages