Gin: bug:c.BindJSON(&req)

Created on 26 Aug 2016  路  5Comments  路  Source: gin-gonic/gin

bug desc

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"}


I think

the int 0 in req body can not unmashal.

Most helpful comment

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.

All 5 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

boneq picture boneq  路  3Comments

oryband picture oryband  路  3Comments

xpbliss picture xpbliss  路  3Comments

nxvl picture nxvl  路  3Comments

rawoke083 picture rawoke083  路  3Comments