Erick Li
Erick Li

Reputation: 121

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

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

Upvotes: 11

Views: 29941

Answers (2)

KAMAL
KAMAL

Reputation: 61

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

Upvotes: 6

Gokhan Sari
Gokhan Sari

Reputation: 7994

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

Upvotes: 23

Related Questions