From 5460b28fa4fa3d14e8c9a8c935cd727260c3f1a4 Mon Sep 17 00:00:00 2001 From: gpzhou Date: Wed, 27 May 2020 17:53:39 +0800 Subject: [PATCH 1/2] reuse http.request.Body --- context.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index a9458833..8992e2d4 100644 --- a/context.go +++ b/context.go @@ -5,6 +5,7 @@ package gin import ( + "bytes" "errors" "fmt" "io" @@ -78,6 +79,9 @@ type Context struct { // SameSite allows a server to define a cookie attribute making it impossible for // the browser to send this cookie along with cross-site requests. sameSite http.SameSite + + // rawData cache and reuse http.request.Body + rawData []byte } /************************************/ @@ -485,6 +489,10 @@ func (c *Context) initFormCache() { if c.formCache == nil { c.formCache = make(url.Values) req := c.Request + if req.Body != nil { + c.rawData, _ = ioutil.ReadAll(req.Body) + req.Body = ioutil.NopCloser(bytes.NewReader(c.rawData)) + } if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { if err != http.ErrNotMultipart { debugPrint("error on parse multipart form array: %v", err) @@ -792,7 +800,8 @@ func (c *Context) GetHeader(key string) string { // GetRawData return stream data. func (c *Context) GetRawData() ([]byte, error) { - return ioutil.ReadAll(c.Request.Body) + // return ioutil.ReadAll(c.Request.Body) + return c.rawData, nil } // SetSameSite with cookie From 7b5e0399987ea10085e499e51b2e1da9b7e13495 Mon Sep 17 00:00:00 2001 From: fair Date: Wed, 27 May 2020 19:21:50 +0800 Subject: [PATCH 2/2] add init --- context.go | 1 + 1 file changed, 1 insertion(+) diff --git a/context.go b/context.go index 8992e2d4..619cfd21 100644 --- a/context.go +++ b/context.go @@ -801,6 +801,7 @@ func (c *Context) GetHeader(key string) string { // GetRawData return stream data. func (c *Context) GetRawData() ([]byte, error) { // return ioutil.ReadAll(c.Request.Body) + c.initFormCache() return c.rawData, nil }