英文:
Validate struct field if it exists
问题
我正在将一个JSON用户对象POST到我的Golang应用程序中,我将'req.body'解码为'User'结构体。
err := json.NewDecoder(req.Body).Decode(user)
//如果有错误,处理错误
以及'User'结构体:
type User struct {
Name string json:"name,omitempty"
Username string json:"username,omitempty"
Email string json:"email,omitempty"
Town string json:"town,omitempty"
//更多字段在这里
}
虽然我不需要实际验证的帮助,但我想知道如何仅在用户名作为JSON对象的一部分包含时才验证它。目前,如果未包含用户名,则'User.Username'仍将存在但为空,即""
我如何检查是否作为POST对象的一部分包含了'username'?
英文:
I'm POSTing a JSON user object to my Golang application where I decode the 'req.body' into a 'User' struct.
err := json.NewDecoder(req.Body).Decode(user)
//handle err if there is one
and the 'User' struct:
type User struct {
Name string `json:"name,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Town string `json:"town,omitempty"`
//more fields here
}
While I don't need help with the actual validation, I would like know how to validate usernames only if it is included as part of the JSON object. At the moment, if a username isn't included then User.Username
will still exist but be empty i.e. ""
How can I check to see if '"username"' was included as part of the POSTed object?
答案1
得分: 13
你可以使用指向字符串的指针:
type User struct {
Name string `json:"name,omitempty"`
Username *string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Town string `json:"town,omitempty"`
//more fields here
}
func main() {
var u, u2 User
json.Unmarshal([]byte(`{"username":"hi"}`), &u)
fmt.Println("username set:", u.Username != nil, *u.Username)
json.Unmarshal([]byte(`{}`), &u2)
fmt.Println("username set:", u2.Username != nil)
fmt.Println("Hello, playground")
}
英文:
You can use a pointer to a string:
type User struct {
Name string `json:"name,omitempty"`
Username *string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Town string `json:"town,omitempty"`
//more fields here
}
func main() {
var u, u2 User
json.Unmarshal([]byte(`{"username":"hi"}`), &u)
fmt.Println("username set:", u.Username != nil, *u.Username)
json.Unmarshal([]byte(`{}`), &u2)
fmt.Println("username set:", u2.Username != nil)
fmt.Println("Hello, playground")
}
答案2
得分: 1
添加到上面的答案中。请注意,验证函数的顺序很重要。我之前遇到错误是因为我将UUIDV4验证标签放在了omitempty之前:
ParentID *string `json:"parent_id" validate:"uuid4,omitempty"`
正确的方式是:
ParentID *string `json:"parent_id" validate:"omitempty,uuid4"`
英文:
To add to the above answer. Note that the order of the validate functions is important. I was getting the error because I was placing the UUIDV4 validation tag before the omitempty:
ParentID *string `json:"parent_id" validate:"uuid4,omitempty"`
Correct way is:
ParentID *string `json:"parent_id" validate:"omitempty,uuid4"`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论