Fiber: ๐Ÿค” How to use BodyParser with multiple structs?

Created on 13 May 2020  ยท  6Comments  ยท  Source: gofiber/fiber

โ™ป Wait for Response

Most helpful comment

Create a new struct that holds your incoming JSON format with all those structs used?

Example:

type User struct {
  ...
}

...

type IncomingData struct {
  User
  Address
  Cart
}
data := IncomingData{}
err := c.BodyParser(&data)

All 6 comments

Thanks for opening your first issue here! ๐ŸŽ‰ Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Create a new struct that holds your incoming JSON format with all those structs used?

Example:

type User struct {
  ...
}

...

type IncomingData struct {
  User
  Address
  Cart
}
data := IncomingData{}
err := c.BodyParser(&data)

So it means that BodyParser can only dump the body into one and just one struct, then? I need to decompose it manually, right?

Hi @phtdacosta ,
Could you explain what exactly you mean by multiple structs a little further?
Do you mean nested structs, or different structs next to each other from a JSON dictionary?

@phtdacosta

You can even unmarshal the contents into different structs using pointers in go?

type User struct {
    Name string `json:"name"`
        ...
}

...

type IncomingData struct {
    *User
    Cart
    AddressArr []Address `json:"addresses"`
}

user := &User{}
data := IncomingData{
    User: user,
}

err := ctx.BodyParser(&data)

I'm closing this issue since the question has been answered.

Was this page helpful?
0 / 5 - 0 ratings