Golang gin-gonic JSON绑定

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

Golang gin-gonic JSON binding

问题

我有以下结构体:

  1. type foos struct {
  2. Foo string `json:"foo" binding:"required"`
  3. }

我有以下端点:

  1. func sendFoo(c *gin.Context) {
  2. var json *foos
  3. if err := c.BindJSON(&json); err != nil {
  4. c.AbortWithStatus(400)
  5. return
  6. }
  7. // 对 json 做一些处理
  8. }

当我发送以下 JSON:

  1. {"bar":"bar bar"}

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

  1. func sendFoo(c *gin.Context) {
  2. var json foos // 移除指针
  3. if err := c.BindJSON(&json); err != nil {
  4. c.AbortWithStatus(400)
  5. return
  6. }
  7. // 对 json 做一些处理
  8. }

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

英文:

I have the struct below

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

and I have the following endpoint

  1. func sendFoo(c *gin.Context) {
  2. var json *foos
  3. if err := c.BindJSON(&json); err != nil {
  4. c.AbortWithStatus(400)
  5. return
  6. }
  7. // Do something about json
  8. }

when I post this JSON

  1. {"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,

  1. func sendFoo(c *gin.Context) {
  2. var json foos //remove pointer
  3. if err := c.BindJSON(&json); err != nil {
  4. c.AbortWithStatus(400)
  5. return
  6. }
  7. // Do something about json
  8. }

binding works and the err is not nil. Why?

答案1

得分: 7

这段内容的翻译如下:

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

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

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

英文:

It is documented in binding.go, lines 25-32 :

  1. type StructValidator interface {
  2. // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
  3. // If the received type is not a struct, any validation should be skipped and nil must be returned.
  4. // If the received type is a struct or pointer to a struct, the validation should be performed.
  5. // If the struct is not valid or the validation itself fails, a descriptive error should be returned.
  6. // Otherwise nil must be returned.
  7. ValidateStruct(interface{}) error
  8. }

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:

确定