Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This seems like a judiciously designed API to me.

You don't need to check if err was nil before calling resp.Body.Close()

https://pkg.go.dev/net/http#Get

> When err is nil, resp always contains a non-nil resp.Body. Caller should close resp.Body when done reading from it.

https://pkg.go.dev/net/http#Response

> The http Client and Transport guarantee that Body is always non-nil, even on responses without a body or responses with a zero-length body. It is the caller's responsibility to close Body.

Calling http.Get() returns an object that symbolises the response. The response body itself might be multiple terabytes, so http.Get() shouldn't read it for you, but give you a Reader of some sort.

The question then is, when does the Reader get closed? The answer should be "when the caller is done with it". This can't be automatic handled when the resp object goes out of scope, as it would preclude the caller e.g. passing the response to another goroutine for handling, or putting it in an array, or similar.

Go tooling is more than happy to tell you that there's an io.ReadCloser in one of the structs returned to you, and it can see that you didn't Close() it, store it, or pass it to somewhere else, before the struct it was in went out of scope.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: