[英]Golang gin-gonic JSON binding
我有下面的结构
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
}
绑定有效并且错误不是nil。 为什么?
它记录在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会收到一个指向结构的指针,并且如文档所述,不会进行任何检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.