简体   繁体   English

Golang Gin-Gonic JSON绑定

[英]Golang gin-gonic JSON binding

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 当我发布这个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. 绑定有效并且错误不是nil。 Why? 为什么?

It is documented in binding.go , lines 25-32 : 它记录在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
}

In your case, ValidateStruct receives a pointer to a pointer to a struct, and no checking takes place, as documented. 在您的情况下,ValidateStruct会收到一个指向结构的指针,并且如文档所述,不会进行任何检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM