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

Viewed 9481

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)
}
2 Answers

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- 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"`    
}

2- In your view you can get it like this:

app.Post("/post", func(c *fiber.Ctx) error {
    user := new(User)

    if err := ctx.BodyParser(user); err != nil {
      fmt.Println("error = ",err)
      return ctx.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)
}

Related