gpt4 book ai didi

json - 通过 application/json curl 请求发送 bool 值

转载 作者:IT王子 更新时间:2023-10-29 02:21:36 30 4
gpt4 key购买 nike

我正在尝试发送 curl 请求。这是我的要求:

curl -H "Content-Type: application/json" -X POST -d '{"username":"tahereh","password":"1234", "admin":true}' http://localhost:8000/users

我在我的代码中解码此请求并将其存储在代码的用户结构的“用户变量”中,如下所示:

var newUser models.User //User is an struct in model package
err1 := json.NewDecoder(r.Body).Decode(&newUser)

然后我使用 dlv debug 命令行调试我的代码。我的问题是当我在 dlv 中使用 print newUser 打印 newUser 时,除 bool 值外,所有变量都正确设置。当我通过 curl 请求发送真实值时,它设置为 false!

要点:我打印了err1,也是null。

最佳答案

在您的 models.User 类型中,您明确指定从 JSON 处理中排除 Admin 字段(这就是 json:"-" tag value means), 所以它的值留给它的zero value (对于 bool 类型为 false)。

将其标签更改为 json:"admin",因此其值将从 JSON "admin" 属性中设置,如本例所示:

type User {
// your other fields...
Admin bool `json:"admin" gorm:"not null;default=false"`
}

在此处阅读有关结构标签的更多信息:What are the use(s) for tags in Go?

关于json - 通过 application/json curl 请求发送 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46500712/

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