Disable json binding validation

Viewed 518

I'm using gin for creating web services.

gin has Bind(&request) which validates the request based on the tags provided in struct. If the validation fails, it returns an error.

But I want the invalid request to be logged. How do I get the request json?

  type SignupRequest struct {
    FirstName      string `json:"first_name" binding:"required"`
    AssociatedBank string `json:"associated_bank" binding:"required"`
}

...

srj := NewSignupRequest()
err = c.Bind(srj)

If the required fails, I won't have the request data to log.

1 Answers

Two options come to mind.

  1. To do this all within Gin, use c.ShouldBindWithBody(...) which has a side effect of storing the request body in the context key/value map under the key gin.Context.BodyBytesKey. Here is the implementation of ShouldBindWithBody for reference: https://github.com/gin-gonic/gin/blob/master/context.go#L711

  2. Beyond that, you can access the request itself from the gin.Context as c.Request. This is a standard net/http.Request with all the available functionality listed here: https://golang.org/pkg/net/http/#Request (reading body, headers, etc.).

For option 2, I haven't tested this myself, but I would expect that since c.Bind(...) is reading from the request body behind the scenes, you might find that reading from c.Request.Body after c.Bind() fails doesn't give you the full request body (it's already been at least partially, if not fully, read in c.Bind()). In that case, you may have to tweak your code to read from the request yourself into a byte buffer and then do the binding (marshalling) from the byte buffer to SignupRequest yourself. In that way, you'll have the raw bytes to log or do whatever else you want with if the binding fails.

Related