8

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

{
    "name" : "John Wick"
    "email" : "johnw@gmail.com"
}
app.Post("/post", func(c *fiber.Ctx) error {
    //read the req.body here
    name := req.body.name
    return c.SendString(name)
}
Gokhan Sari
  • 7,185
  • 5
  • 34
  • 32
Erick Li
  • 91
  • 1
  • 1
  • 2

2 Answers2

17

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)
}
Gokhan Sari
  • 7,185
  • 5
  • 34
  • 32
4
  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)
}
Eric
  • 795
  • 5
  • 21
KAMAL
  • 41
  • 1