To add @Mihailo option # 2, call it option # 2.1 Define the dclose() function as follows:
func dclose(c io.Closer) { if err := c.Close(); err != nil { log.Fatal(err) } }
use like this:
defer dclose(resp.Body)
Also in your code, checking for err!=nil may declare:
func errcheck(err error) { if err != nil { log.Fatal(err) } }
then use:
errcheck(err)
then your code will look like this:
resp, err := http.Get("http://example.com/") errcheck(err) defer dclose(resp.Body) body, err := ioutil.ReadAll(resp.Body) errcheck(err) fmt.Printf("%s", string(body))
IMHO a little cleaner, maybe? But I'll wait for the go fan to fix me and highlight the flaws.
EDIT
Thanks! @RayfenWindspear
Replace log.Fatal(err) with log.Println(err) to avoid unnecessary panic.
EDIT2
dclose() to avoid confusion with go close()
Good luck
source share