gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:03:27 26 4
gpt4 key购买 nike

我有下面的结构

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com