Validate struct field if it exists

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

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:

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

playground



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!