Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to close the body of a request once you have inspected it?

Tags:

go

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?

like image 352
Alex Avatar asked May 11 '18 00:05

Alex


1 Answers

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.

like image 70
ban Avatar answered Oct 26 '22 07:10

ban