Please see the example here https://pkg.go.dev/net/http#example-Get. The snipped below as well:
func main() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
body, err := io.ReadAll(res.Body)
res.Body.Close() // Why!?
if res.StatusCode > 299 {
log.Fatalf("Response failed with status code: %d and\nbody: %s\n", res.StatusCode, body)
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", body)
}
My question is: Why do I need to close the res.Body.Close()
in line no 7. I did not open it. I see the explanation in What could happen if I don't close response.Body? and I understand that documentation says so.
Could there be a better way of solving this?
I think this is breaking the open/close principle. I think if ReadAll opened the steam it should close it. Is this usually how those things are done in Go?