Gin: use c.Request.Body needs Close?

Created on 24 Jan 2018  路  3Comments  路  Source: gin-gonic/gin

func Test(c *gin.Context) {
defer c.Request.Body.Close()

b, _ := ioutil.ReadAll(c.Request.Body)

fmt.Println(string(b))

}

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

All 3 comments

@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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

libnat picture libnat  路  29Comments

valyala picture valyala  路  31Comments

miketonks picture miketonks  路  25Comments

mytharcher picture mytharcher  路  28Comments

windweller picture windweller  路  20Comments