Reputation: 121
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
Reputation: 61
type User struct {
Name string `json: "email"`
Email string `json: "email"`
}
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
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