Handle optional JSON field in HTTP request body

You want to use the omitempty option

type MyStruct struct {
    Name  string `json:"name,omitempty"`
    Age   int    `json:"age"`
    Email string `json:"email,omitempty"`
}

If you want Age to be optional as well you have to use a pointer, since the zero value of an int isn’t really “empty”

type MyStruct struct {
    Name  string `json:"name,omitempty"`
    Age   *int   `json:"age,omitempty"`
    Email string `json:"email,omitempty"`
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)