I'm using Go and Buffalo to develop an API. When receiving a request, it is possible to automatically map the JSON payload to a struct:
func MyAction(c buffalo.Context) error {
u := &User{}
if err := c.Bind(u); err != nil {
return err
}
u.Name // "Ringo"
u.Email // "ringo@beatles.com"
}
However, it supposes that the payload is of this shape:
{
"name": "Ringo",
"email": "ringo@beatles.com"
}
If for some reason, the incoming payload has a key:
{
"user": {
"name": "Ringo",
"email": "ringo@beatles.com"
}
}
The binding won't work. I couldn't find how to handle this case. How should I approach this ?
Perhaps you can wrap your struct with map[string]User{}
, here is an example:
func MyAction(c buffalo.Context) error {
u := map[string]User{
"user": User{},
}
if err := c.Bind(&u); err != nil {
return err
}
user := u["user"]
user.Name // "Ringo"
user.Email // "ringo@beatles.com"
}
In my opinion define a struct would be cleaner solution:
type UserObject struct {
User struct {
Email string
Name string
}
}
func MyAction(c buffalo.Context) error {
u := UserObject{}
if err := c.Bind(&u); err != nil {
return err
}
user := u.User
user.Name // "Ringo"
user.Email // "ringo@beatles.com"
}