gpt4 book ai didi

rest - c.BindJSON 带可选参数

转载 作者:IT王子 更新时间:2023-10-29 01:21:44 24 4
gpt4 key购买 nike

我正在使用 go-gin 并尝试实现 PATCH API。 3 个字段是可编辑的,所以我有一个这样定义的结构

type Person struct {
Name string `form:"name" json:"name" binding:"required"`
Account string `form:"account" json:"account" binding:"required"`
PrimaryOwner string `form:"primary_owner" json:"primary_owner" binding:"required"`
}

我正在尝试像这样绑定(bind) json:

var json Person
if c.BindJSON(&json) == nil {
fmt.Println("json matched!!!!!!!")
}else {
fmt.Println("json not matched!!!!!!!")
}

问题是它试图绑定(bind)所有参数。如果我给出所有参数,它就会匹配,但即使缺少一个参数,它也会进入 else block 。在补丁 API 中,我不想强​​制绑定(bind)。如果我从所有字段中删除 binding:"required" 它总是匹配,即使我提供了一些像 sdfsdfsdf 的键。如何绑定(bind)到所有参数而不是全部在一起。应验证 json 请求正文中的 key ,但不应同时要求所有 key 。

最佳答案

刚发现那个问题没有答案。

所以你想绑定(bind)所有的参数并且最少需要一个

How can make binding to all parameters but not all together.

您几乎在这里回答了您的问题:

If I remove binding:"required" from all fields it always matches

所以我会删除必需项并检查每个值。

var json Person
if err := c.BindJSON(&json); err != nil {
// error handling here
// something went wrong
}
if json.Name == "" && json.Account == "" && json.PrimaryOwner == "" {
// no key is given...
}
}

关于rest - c.BindJSON 带可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39826703/

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