While working on REST APIs, we usually ensure the response body is closed. However, a colleague suggested that the request body should also be closed. From what I’ve read in various blogs, it seems there’s no need to explicitly close the request body as the server automatically handles it.
My questions are:
Is it necessary to close the request body? If yes:
a. Who is responsible for closing the request body — the client or the server?
b. Do we need to explicitly close the request body, or is it automatically closed by the client/server?
This depends on the situation. The following is an example of http1:
http server:
It can be seen that after ServeHTTP is executed, w.finishRequest() is performed, and the body of req is closed internally.
go1.23.3/src/net/http/server.go:2098
For response, this does not need to be handled by the developer.
http client:
For the body of req, it will be actively closed internally in do(req *Request).
go1.23.3/src/net/http/client.go:595
For response, this needs to be handled manually by the developer.