Fiber: Hi guys! how do i use BodyParser with a nested struct? 馃馃

Created on 5 Sep 2020  路  4Comments  路  Source: gofiber/fiber

I trying to use bodyparser to parse a nested struc from a form, do i have to specify something on field name?

For example

type Job struct {
    Type string `json:"type" xml:"type" form:"type"`
    Salary string `json:"salary" xml:"salary" form:"salary"`
}

type Person struct {
    Name string `json:"name" xml:"name" form:"name"`
    Pass string `json:"pass" xml:"pass" form:"pass"`
    Job Job `what goes on here?`
}

app.Post("/AddNewPerson", func(c *fiber.Ctx) {
        p := new(Person)

        if err := c.BodyParser(p); err != nil {
            log.Fatal(err)
        }

        log.Println(p.Name) // john
        log.Println(p.Job.Type) // software engineer
})


Sorry if this is a really obvious question, i am quite new to go and fiber

馃 Question

All 4 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

type Person struct {
    Name string `json:"name" xml:"name" form:"name"`
    Pass string `json:"pass" xml:"pass" form:"pass"`
    Job Job `json:"job" xml:"job" form:"job"`
}

You can also convert your payload to structs using https://mholt.github.io/json-to-go/

You can try this demo

package main

import (
    "github.com/gofiber/fiber"
    "log"
)

func main() {
    app := fiber.New()

    type Job struct {
        Type   string `json:"type" xml:"type" form:"type"`
        Salary string `json:"salary" xml:"salary" form:"salary"`
    }

    type Person struct {
        Name string `json:"name" xml:"name" form:"name"`
        Pass string `json:"pass" xml:"pass" form:"pass"`
        Job  Job    `json:"job"` // or nothing to default
    }

    app.Post("/AddNewPerson", func(c *fiber.Ctx) {
        p := new(Person)

        if err := c.BodyParser(p); err != nil {
            log.Fatal(err)
        }

        c.SendString(p.Name + ":" + p.Job.Type)
    })

    log.Println(app.Listen(":3000"))
}

And the result

http post :3000/AddNewPerson name=jhon pass=pass job:='{"type":"software engineer"}'
HTTP/1.1 200 OK
Content-Length: 22
Content-Type: text/plain; charset=utf-8
Date: Sat, 05 Sep 2020 04:59:29 GMT

jhon:software engineer

Thank you, guys!

Was this page helpful?
0 / 5 - 0 ratings