Golang gin-gonic JSON绑定

huangapple go评论75阅读模式
英文:

Golang gin-gonic JSON binding

问题

我有以下结构体:

type foos struct {
    Foo string `json:"foo" binding:"required"`
}

我有以下端点:

func sendFoo(c *gin.Context) {
    var json *foos

    if err := c.BindJSON(&json); err != nil {
        c.AbortWithStatus(400)
        return
    }

    // 对 json 做一些处理
}

当我发送以下 JSON:

{"bar":"bar bar"}

err 总是为 nil。我已经写了 binding:"required",但它不起作用。但是当我将端点更改为以下形式时:

func sendFoo(c *gin.Context) {
    var json foos // 移除指针

    if err := c.BindJSON(&json); err != nil {
        c.AbortWithStatus(400)
        return
    }

    // 对 json 做一些处理
}

绑定起作用,err 不为 nil。为什么会这样?

英文:

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

得分: 7

这段内容的翻译如下:

binding.go 的第25-32行有相关文档:

type StructValidator interface {
    // ValidateStruct 可以接收任何类型,并且不应该引发 panic,即使配置不正确。
    // 如果接收到的类型不是结构体,则应跳过任何验证,并返回 nil。
    // 如果接收到的类型是结构体或结构体指针,则应进行验证。
    // 如果结构体无效或验证本身失败,则应返回描述性错误。
    // 否则,必须返回 nil。
    ValidateStruct(interface{}) error
}

在你的情况下,ValidateStruct 接收一个指向结构体指针的指针,并且不进行任何检查,正如文档中所述。

英文:

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.

huangapple
  • 本文由 发表于 2017年3月12日 15:13:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/42744784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定