In a gofiber POST request how can I parse the request body?

24.4k Views Asked by At

How would I read and change the values if I posted JSON data to /post route in gofiber:

{
    "name" : "John Wick"
    "email" : "[email protected]"
}
app.Post("/post", func(c *fiber.Ctx) error {
    //read the req.body here
    name := req.body.name
    return c.SendString(name)
}
2

There are 2 best solutions below

0
On

You can use BodyParser

app.Post("/post", func(c *fiber.Ctx) error {
    payload := struct {
        Name  string `json:"name"`
        Email string `json:"email"`
    }{}

    if err := c.BodyParser(&payload); err != nil {
        return err
    }

    return c.JSON(payload)
}
1
On
  1. let's say the name and email are for a user, so first you create a user struct:
type User struct {
    Name string `json: "email"`
    Email string `json: "email"`    
}
  1. In your view you can get it like this:
app.Post("/post", func(c *fiber.Ctx) error {
    user := new(User)

    if err := c.BodyParser(user); err != nil {
        fmt.Println("error = ",err)
        return c.SendStatus(200)
    }

    // getting user if no error
    fmt.Println("user = ", user)
    fmt.Println("user = ", user.Name)
    fmt.Println("user = ", user.Email)

    return c.SendString(user.Name)
}