Golang gin-gonic JSON 绑定

Wis*_*oyo 1 json pointers go

我有下面的结构

type foos struct { Foo string `json:"foo" binding:"required"`}
Run Code Online (Sandbox Code Playgroud)

我有以下端点

  func sendFoo(c *gin.Context) {
      var json *foos

      if err := c.BindJSON(&json); err != nil {
          c.AbortWithStatus(400)
          return
      }

      // Do something about json
   }
Run Code Online (Sandbox Code Playgroud)

当我发布此 JSON 时

{"bar":"bar bar"}
Run Code Online (Sandbox Code Playgroud)

错误始终为零。我写了需要绑定,但它不起作用。但是当我像下面这样更改端点时,

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
}
Run Code Online (Sandbox Code Playgroud)

绑定有效,错误不是零。为什么?

Zoy*_*oyd 6

它记录在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
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下, ValidateStruct 接收一个指向指向结构的指针的指针,并且没有进行检查,如文档所述。