I'm attempting to enforce required JSON request fields using the binding="required" tag. I expected c.BindJSON to raise an error when a required field was not present, however, it also raises an error when a required bool field is set to false.
Is there a better way to enforce required JSON request bodies?
Here is an example:
func myHandler(c *gin.Context) {
var req struct {
Foo string `json:"foo" binding="required"`
Bar bool `json:"bar" binding="required"`
}
if err := c.BindJSON(&req); err != nil {
// When a request's `foo` field is set to `false`, the following error is raised:
// err="Key: '.Foo' Error:Field validation for 'Foo' failed on the 'required' tag"
}
}
Looks like using a *bool will produce the desired behavior.
This may be worthwhile documenting somewhere in the examples.
Just an update to whomever is still stuck with this bug. Addind *bool is not the entire solution. You must change the binding:"required" to binding:"exists".
Here is the documentation to back that up (gin uses this pkg for input obj validations):
https://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Exists
Most helpful comment
Just an update to whomever is still stuck with this bug. Addind *bool is not the entire solution. You must change the
binding:"required"tobinding:"exists".Here is the documentation to back that up (gin uses this pkg for input obj validations):
https://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Exists