Is it necessary to close request body

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:

  1. 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?

Thanks,
Madhusudan

Yes, you must close it.
Something like;

client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
    return nil, err
}
defer resp.Body.Close()

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.

1 Like

I think you misread the question. Madhusudan was referring to req not resp.

Although your advice is good when it comes to working with the resp, closing it is always good practice.

I think it’s need.
I like do http request like this to reuse local port

 client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
    return nil, err
}
_,_=io.ReadAll(resp.Body)
 _=resp.Body.Close()