gin icon indicating copy to clipboard operation
gin copied to clipboard

Problem with `c.BindJSON(&body)` related with use it in middleware to check if the signature is right

Open jefer94 opened this issue 2 years ago • 5 comments

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

jefer94 avatar Dec 07 '22 13:12 jefer94

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

jefer94 avatar Dec 07 '22 13:12 jefer94

How about saving the body using Context.Set and retrieving it with Context.Get?

rnotorni avatar Dec 08 '22 05:12 rnotorni

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)

jefer94 avatar Dec 08 '22 16:12 jefer94

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).

sjy3 avatar Feb 17 '23 09:02 sjy3

That solution does not work with gqlgen

jefer94 avatar May 20 '23 11:05 jefer94