{"id":4943,"date":"2021-01-17T10:23:55","date_gmt":"2021-01-17T04:53:55","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=4943"},"modified":"2021-01-17T18:04:40","modified_gmt":"2021-01-17T12:34:40","slug":"resposne-body-closed-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/resposne-body-closed-golang\/","title":{"rendered":"Why response body is closed in golang"},"content":{"rendered":"\n

The response body should be closed after the response is fully read. This is done to prevent resource leak of connections. If the response body is not closed then the connection will not be released and hence it cannot be reused. From the official docs of http.Client<\/strong><\/p>\n\n\n\n

From the official docs of http.Client<\/strong><\/p>\n\n\n\n

https:\/\/golang.org\/pkg\/net\/http\/#Client<\/a><\/p>\n\n\n\n

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.<\/p>\n\n\n\n

So essentially, transport may not reuse HTTP\/1.x “keep-alive” TCP connections if the Body is not read to completion and closed.The response.Body<\/strong> implements the io.ReadCloser<\/strong> interface.<\/p>\n\n\n\n

Also to mention that it is the caller’s responsibility to close the response body<\/p>\n\n\n\n

Some important guidelines to follow <\/p>\n\n\n\n