简体   繁体   中英

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

{"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?

It is documented in binding.go , lines 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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