type UpdateUserReqParameters struct {
Sender int `form:"sender" json:"sender" binding:"required"`
}
code:
var req UpdateUserReqParameters
if err := c.BindJSON(&req); err != nil {
response.ErrorResponse(c, http.StatusBadRequest, err)
return
}
when i use postman send
{
"sender":0,
}
get this error
r
{err":"Key: 'UpdateUserReqParameters.Sender' Error:Field validation for 'Sender' failed on the 'required' tag"}
the int 0 in req body can not unmashal.
Sender *int `form:"sender" json:"sender" binding:"exists"`
to further the explanation of @stxml
required only ensures that the value is not set to it's defaut value and because in Go values have a default value, in your case Sender will be 0; you can use exists, with your int being *int
please see the documentation here it outlines all of the tags and descriptions of each.
It seems like a common problem. There are several open issues about this exact same thing.
I think better documentation could help here. The paragraph about 'binding' doesn't even mention that it's using validator, which would have more information.
Answer:
type UpdateUserReqParameters struct {
- Sender int `form:"sender" json:"sender" binding:"required"`
+ Sender *int `form:"sender" json:"sender" binding:"exists"`
}
thanks
Most helpful comment
to further the explanation of @stxml
requiredonly ensures that the value is not set to it's defaut value and because in Go values have a default value, in your caseSenderwill be0; you can use exists, with your int being*intplease see the documentation here it outlines all of the tags and descriptions of each.