doucong4535 2017-03-12 07:13
浏览 205
已采纳

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥100 webapi的部署(标签-服务器)
    • ¥20 怎么加快手机软件内部计时的时间(关键词-日期时间)
    • ¥15 C语言除0问题的检测方法
    • ¥15 为什么四分管的内径有的是16mm有的15mm,四分不应该是12.7mm吗
    • ¥15 macos13下 ios交叉编译的问题
    • ¥15 bgz压缩文件怎么打开
    • ¥15 封装dll(引入了pcl的点云设计库)
    • ¥30 关于#开发语言#的问题:我需要在抄板的基础上再抄板抄程序,根据RDA8851CM基础上开发
    • ¥15 oracle 多个括号,怎么删除指定的括号及里面的内容?
    • ¥15 小新14API2019想用bios调风扇