gpt4 book ai didi

json - 如何在输入时跳过 Struct 中的 JSON 字段并在输出中显示它们,以及在输入中接受某些字段并在 Golang 中在输出中跳过它们?

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

我正在使用 Echo 框架和 Gorm 在 Go 中编写网络服务。我有一个如下所示的 User 结构:

type User struct {
ID uint `json:"user_id"`
Email string `json:"email_address,omitempty" validate:"required,email"`
}

我正在接受带有 Content-type: application/jsonPOST 请求。我希望我的输入是 {"email_address": "email@email.com"} 并且我的输出是 {"user_id": 1}

如何禁止用户在请求中提交ID(这样他们就不能创建具有特定ID的记录),但保留ID在响应中?现在我正在保存之前执行 user.ID = 0,但我想知道是否有更好的方法来做到这一点?

我还想在输出中跳过 Email。现在我正在输出之前执行 user.Email = "" 。还有更好的方法吗?

谢谢!

最佳答案

虽然 icza 的回答提出了一个很好的解决方案,但您也可以使用 JSON 编码辅助方法 MarshalJSON/UnmarshalJSON:

func main() {
// employing auxiliary json methods MarshalJSON/UnmarshalJSON
user := User{ID: 123, Email: `abc@xyz.com`}
js, _ := json.Marshal(&user)
log.Printf("%s", js)

input := UserInput(user)
js, _ = json.Marshal(&input)
log.Printf("%s", js)

output := UserOutput(user)
js, _ = json.Marshal(&output)
log.Printf("%s", js)
}

type User struct {
ID uint `json:"user_id"`
Email string `json:"email_address,omitempty" validate:"required,email"`
}

type UserInput User

func (x *UserInput) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Email string `json:"email_address,omitempty" validate:"required,email"`
}{
Email: x.Email,
})
}

type UserOutput User

func (x *UserOutput) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
ID uint `json:"user_id"`
}{
ID: x.ID,
})
}

这给了我们:

[  info ] main.go:25: {"user_id":123,"email_address":"abc@xyz.com"}
[ info ] main.go:29: {"email_address":"abc@xyz.com"}
[ info ] main.go:33: {"user_id":123}

关于 Go Playground .

关于json - 如何在输入时跳过 Struct 中的 JSON 字段并在输出中显示它们,以及在输入中接受某些字段并在 Golang 中在输出中跳过它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42086071/

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