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.

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

报告相同问题?

悬赏问题

  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题
  • ¥20 请问有人知道怎么用工艺库里面的sdb文件通过virtuoso导出来library里面每个cell的symbol吗?
  • ¥20 海思 nnie 编译 报错
  • ¥50 决策面并仿真,要求有仿真结果图
  • ¥15 关于路由器的路由协议配置
  • ¥15 springboot接入微信支付SDK
  • ¥50 大区域的遥感影像匹配 怎么做啊
  • ¥15 求解答:pytorch跑yolov8神经网络受挫
  • ¥20 Js代码报错问题不知道怎么解决