Is resp.Body.Close () necessary if we don't read anything from the body?

I have a function that just makes a receive request to check the status code. He does not read anything from the body. Should I still complete the function with resp.Body.Close() ?

Callers should close resp.Body when finished reading from it. If resp.Body is not closed, the Client underlying RoundTripper (usually Transport) may not be able to reuse a permanent TCP connection to the server for a subsequent keep-alive request.

+8
go
source share
1 answer

Yes. When you call http.Get, the function returns a response as soon as all HTTP headers are read. The body of the response has not yet been read. Response.Body is a wrapper for network connection to the server. When you read it, it loads the body of the response.

.Close () tells the system what you did with the network connection. If you have not read the response body, the http connection closes by default. (A transport can only reuse a connection if the body was read, because if it reused the connection with an unread body, the next request made using this connection will receive a previous response request!)

Therefore, reading the body is often more efficient than just Close () ing if you are making multiple requests, especially with TLS connections, which are relatively expensive to create.

If you do not need a response body, you should use Head instead of Get. The head does not require reading or closing the response body.

+15
source share

All Articles