I have the struct below
type foos struct { Foo string `json:"foo" binding:"required"`}
and I have the following endpoint
func sendFoo(c *gin.Context) {
var json *foos
if err := c.BindJSON(&json); err != nil {
c.AbortWithStatus(400)
return
}
// Do something about json
}
when I post this JSON
{"bar":"bar bar"}
the err is always nil. I write binding required and it doesn't work. But when I change the endpoint like below,
func sendFoo(c *gin.Context) {
var json foos //remove pointer
if err := c.BindJSON(&json); err != nil {
c.AbortWithStatus(400)
return
}
// Do something about json
}
binding works and the err is not nil. Why?
c.BindJSON(json)
in the first case? – zerkmsvar json *foos = &foos{}
orjson := &foos{}
and simply passjson
? – zerkmsvar json *foos
and you just usec.BindJSON(json)
it's return unmarshal error because json is the value of *foos which is nil, and &json will pass the pointer address which will initialized in json.decode. – Wisnu Wardoyo&json
for a variable of*foos
type you get a pointer to a pointer. It correctly tells you about it beingnull
since you did not initialise it, likejson := &foos{}
– zerkms