验证结构字段是否存在

huangapple go评论73阅读模式
英文:

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")
}

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")
}

<kbd>playground</kbd>

答案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:&quot;parent_id&quot; validate:&quot;uuid4,omitempty&quot;`

Correct way is:

ParentID    *string `json:&quot;parent_id&quot; validate:&quot;omitempty,uuid4&quot;`

huangapple
  • 本文由 发表于 2015年7月20日 03:17:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/31504975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定