I have seen several examples where you read from r.Body
and then do a defer r.Body.Close()
right after. What will happen if we do not close it?
Lets say I have a http.Handler
and inside it I decode the contents of r.Body like this:
func createFeedback(w http.ResponseWriter, r *http.Request) {
// ... Some code ...
f := feedback.New()
if err := json.NewDecoder(r.Body).Decode(f); err != nil {
return err
}
defer r.Body.Close()
// ... Some more code ...
}
Why do we have to close r.Body
?
This is done to prevent resource leak of connections. There goes a phrase in the official go documentation:
https://pkg.go.dev/net/http#Client
If the Body is not both read to EOF and closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With