Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate struct field if it exists

Tags:

go

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?

like image 375
tommyd456 Avatar asked Jul 19 '15 19:07

tommyd456


1 Answers

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

like image 136
OneOfOne Avatar answered Oct 13 '22 11:10

OneOfOne