doucong4535
2017-03-12 07:13
浏览 203

Golang Gin-Gonic JSON绑定

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?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumaogui5937 2017-03-12 09:09
    已采纳

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题