Closed Clivern closed 5 years ago
c.GetRawData()
only call one time, it has nothing to do with middleware
@thinkerou i was thinking it is a good idea to make it accessible multiple times and it can be done BTW. Middlewares most of times used as logging layers to incoming requests but anyway there is an available approach so this issue can be closed.
@Clivern Would be nice id you share the available approach. I'm trying to get Raw request data after c.ShouldBindJSON(...), but as mentioned in documentation, after the binding, the body is not available.
Thanks !
@duktig-dev I've shared the working example above. So you can store the request body on a local variable then use c.ShouldBindJSON(...)
then assign it back ... etc
import (
"io/ioutil"
"bytes"
)
r.POST("/test", func(c *gin.Context) {
var bodyBytes []byte
if c.Request.Body != nil {
bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
}
// Access Request Body
c.ShouldBindJSON(...)
// Assign Back the request body
c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
// Access Request Body Again
c.GetRawData()
})
@Clivern Thank you!
Description
Request body disappear on controller if we access it on middleware or two times on general. but this can be fixed if we read the body and then reassign the body again on
GetRawData
method.Code
Do a curl request
The gin log
[GIN-debug] POST /test --> main.main.func1 (2 handlers) [GIN-debug] Listening and serving HTTP on :8080 2018/11/19 10:50:31 first {"key":"app_name","value":"Beaver"} 2018/11/19 10:50:31 second
Do a curl request
The gin log
[GIN-debug] POST /test --> main.main.func1 (2 handlers) [GIN-debug] Listening and serving HTTP on :8080 2018/11/19 11:17:41 first {"key":"app_name","value":"Beaver"} 2018/11/19 11:17:41 second {"key":"app_name","value":"Beaver"}