json - Golang gin-gonic JSON 绑定(bind)

标签 json pointers go

我有下面的结构

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
      }

      // Do something about json
   }

当我发布这个 JSON 时

{"bar":"bar bar"}

错误总是零。我写了 binding required 但它不起作用。但是当我像下面这样更改端点时,

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
}

绑定(bind)有效并且错误不为零。为什么?

最佳答案

记录在 binding.go 中, 第 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
}

在您的例子中,ValidateStruct 收到一个指向结构指针的指针,并且没有进行检查,如记录的那样。

关于json - Golang gin-gonic JSON 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744784/

相关文章:

json - 如何在 iOS5 中将 JSON 数据对象发布到服务器?

java - Spring 3.2 和 jackson 2 : add custom object mapper

c++ - 无法将 [[Float]] 数组传递给 Objective-C++

go - 无法将 POST 正文绑定(bind)到 Go 中的 URL

constructor - "constructors"是否有标准的惯用 Go?

c# - nHibernate 转 Json

javascript - 如何从 JSON 数组中检索 JSON 数据?

c - 我是否误解了这个关于字符串文字范围的例子?

c - 为什么要打印两个指针减去警告的结果?

go - 错误 "cannot download, $GOPATH not set."