BodyParser

Binds the request body to a struct. BodyParser supports decoding query parameters and the following content types based on the Content-Type header:

  • application/json
  • application/xml
  • application/x-www-form-urlencoded
  • multipart/form-data
  1. c.BodyParser(out interface{}) error
  1. // Field names should start with an uppercase letter
  2. type Person struct {
  3. Name string `json:"name" xml:"name" form:"name"`
  4. Pass string `json:"pass" xml:"pass" form:"pass"`
  5. }
  6. app.Post("/", func(c *fiber.Ctx) {
  7. p := new(Person)
  8. if err := c.BodyParser(p); err != nil {
  9. log.Fatal(err)
  10. }
  11. log.Println(p.Name) // john
  12. log.Println(p.Pass) // doe
  13. })
  14. // Run tests with the following curl commands
  15. // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000
  16. // curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000
  17. // curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000
  18. // curl -X POST -F name=john -F pass=doe http://localhost:3000
  19. // curl -X POST "http://localhost:3000/?name=john&pass=doe"