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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With