Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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

Callers should close resp.Body when done reading from it. If resp.Body is not 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 930
Oguz Bilgic Avatar asked Sep 03 '13 18:09

Oguz Bilgic


People also ask

What happens if response body is not closed?

"If resp. Body is not 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."

Do I need to close response body Golang?

According to the documentation of golang, if the Body inside response is not closed and read to EOF, the client may not re-use a persistent TCP connection to the server.

What happens if you don't use the end () method on an HTTP response object?

End method, no other code line after this will execute. So, if you have any other code that needs to be executed, this will skip executing the code, which might result in a wrong or unexpected behavior.


1 Answers

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

.Close() tells the system that you're done with the network connection. If you have not read the response body, the default http transport closes the connection. (The transport can only re-use the connection if the body has been read, because if it reused a connection with an unread body the next request made using that connection would receive the previous request's response!)

So reading the Body is often more efficient than simply Close()ing if you're making more than one request - especially with TLS connections which are relatively expensive to create.

If you don't need the body of the response, you should use Head instead of Get. Head doesn't require reading or closing the response body.

like image 132
andybalholm Avatar answered Sep 29 '22 13:09

andybalholm