func Test(c *gin.Context) {
defer c.Request.Body.Close()
b, _ := ioutil.ReadAll(c.Request.Body)
fmt.Println(string(b))
}
@IIInsomnia I have the same question. so do we need manually close the Body?
You do not need to close requests' body. gin uses the original net/http
package, net/http
closes them automatically.
gin's handlers are called here.
https://github.com/golang/go/blob/release-branch.go1.10/src/net/http/server.go#L1830
and finishRequest()
closes the body of requests.
https://github.com/golang/go/blob/release-branch.go1.10/src/net/http/server.go#L1835
Yes we don't need to close. I also found the related comments.
// Body is the request's body.
//
// For client requests a nil body means the request has no
// body, such as a GET request. The HTTP Client's Transport
// is responsible for calling the Close method.
//
// For server requests the Request Body is always non-nil
// but will return EOF immediately when no body is present.
// The Server will close the request body. The ServeHTTP
// Handler does not need to.
Body io.ReadCloser
more info: https://github.com/golang/go/blob/master/src/net/http/request.go#L171
Most helpful comment
You do not need to close requests' body. gin uses the original
net/http
package,net/http
closes them automatically.gin's handlers are called here.
https://github.com/golang/go/blob/release-branch.go1.10/src/net/http/server.go#L1830
and
finishRequest()
closes the body of requests.https://github.com/golang/go/blob/release-branch.go1.10/src/net/http/server.go#L1835