gpt4 book ai didi

json - 戈朗 : Validate Struct field of type string to be one of specific values

转载 作者:行者123 更新时间:2023-12-02 01:33:21 24 4
gpt4 key购买 nike

golang 版本:1.18.3

验证器:github.com/go-playground/validator/v10

我想在加载到嵌套结构数据结构后验证传入的 JSON 负载。这是我传入的 JSON 负载,

{
"name": "Duro",
"gender": "MALE",
"tier": 3,
"mobileNumber": "0356874586",
"address": {
"city": "Tokyo",
"street": "Shibaura St"
},
"children":[
{
"title": "Mr",
"lastName": "Takayashi"
}
],
"isEmployed": false,
"requestedAt": "2022-01-10T03:30:12.639Z"
}

这是我的 user.go 文件,

package main

type User struct {
Name string `validate:"required"`
Gender string `validate:"required,oneof=MALE FEMALE"`
Tier *uint8 `validate:"required,eq=0|eq=1|eq=2|eq=3"`
MobileNumber string `validate:"required"`
Email string
Address *Address `validate:"required"`
Children []Child `validate:"required,dive"`
IsEmployed *bool `validate:"required"`
PreferredContactMethod string `validate:"oneof=EMAIL PHONE POST SMS"`
RequestedAt time.Time `validate:"required"`
}
type Address struct {
City string `validate:"required"`
Street string `validate:"required"`
}

type Child struct {
Title string `validate:"required"`
FirstName string
LastName string `validate:"required"`
}

这是我的测试函数

func TestUserPayload(t *testing.T) {
validate := validator.New()
var u User

err := json.Unmarshal([]byte(jsonData), &u)
if err != nil {
panic(err)
}

err := validate.Struct(&u)
if err != nil {
t.Errorf("error %v", err)
}

}

此测试因错误而失败,

error Key: 'User.PreferredContactMethod' Error:Field validation for 'PreferredContactMethod' failed on the 'oneof' tag

发生这种情况是因为 Go 将空字符串分配给 User.PreferredContactMethod 结构字段。由于 PreferredContactMethod 不是必填字段,我不想在 json 有效负载没有此验证错误时看到它。当 json 负载没有 preferredContactMethod 字段时,如何避免出现此错误消息?

如果您有更好的替代方案来实现此验证,也很高兴听到它们。

这是 the code in Go Playground

最佳答案

利用 omitemptyoneof 使验证器库忽略空值或未设置的值。

type User struct {
Name string `validate:"required"`
Gender string `validate:"required,oneof=MALE FEMALE"`
Tier *uint8 `validate:"required,eq=0|eq=1|eq=2|eq=3"`
MobileNumber string `validate:"required"`
Email string
Address *Address `validate:"required"`
Children []Child `validate:"required,dive"`
IsEmployed *bool `validate:"required"`
PreferredContactMethod string `validate:"omitempty,oneof=EMAIL PHONE POST SMS"`
RequestedAt time.Time `validate:"required"`
}

关于json - 戈朗 : Validate Struct field of type string to be one of specific values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72914728/

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