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)
//
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