gin
gin copied to clipboard
Problem with `c.BindJSON(&body)` related with use it in middleware to check if the signature is right
I have a header is coming with the signature of the body, and that body is a JSON, I need read the body in a middleware, and then I need to use the body inside of endpoint to manage the request, my question is, how I can get the body two times, or if I can't, how I can solve my issue
That's related to this issue https://github.com/gin-gonic/gin/issues/439 but nothing here is util for this case
Also you need to take in consideration than not exists one way of check the signature of a request without read the body from middleware
How about saving the body using Context.Set and retrieving it with Context.Get?
Let me try this solution, this also works, but in my personal opinion can't revert a reader is not natural, I shouldn't replace the original object in c.Request.Body
var body interface{}
contents, _ := ioutil.ReadAll(c.Request.Body)
c.Request.Body = ioutil.NopCloser(bytes.NewReader(contents))
json.Unmarshal(contents, &body)
in the latest version , gin support func ShouldBindBodyWith to get the body repeatedly , so if you need read the body in a middleware, and then use the body inside of endpoint to manage the request,you can use c.ShouldBindBodyWith(&body, binding.JSON) to replace the c.BindJSON(&body).
That solution does not work with gqlgen