我有下面的结构
type foos struct { Foo string `json:"foo" binding:"required"`}
我有以下端点
func sendFoo(c *gin.Context) {
var json *foos
if err := c.BindJSON(&json); err != nil {
c.AbortWithStatus(400)
return
}
// Do something about json
}
当我发布此JSON
时{"bar":"bar bar"}
错误总是为零。我写了必要的绑定,它不起作用。但是当我像下面那样更改端点时,
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
}
绑定工作,错误不是零。为什么呢?
答案 0 :(得分:2)
记录在binding.go,第25-32行:
type StructValidator interface {
// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
// If the received type is not a struct, any validation should be skipped and nil must be returned.
// If the received type is a struct or pointer to a struct, the validation should be performed.
// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
// Otherwise nil must be returned.
ValidateStruct(interface{}) error
}
在您的情况下,ValidateStruct接收指向结构的指针,并且不会发生任何检查,如文档所示。