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/
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.
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. :)