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" query:"name"`
  4. Pass string `json:"pass" xml:"pass" form:"pass" query:"pass"`
  5. }
  6.  
  7. app.Post("/", func(c *fiber.Ctx) {
  8. p := new(Person)
  9.  
  10. if err := c.BodyParser(p); err != nil {
  11. log.Fatal(err)
  12. }
  13.  
  14. log.Println(p.Name) // john
  15. log.Println(p.Pass) // doe
  16. })
  17. // Run tests with the following curl commands
  18.  
  19. // curl -X POST -H "Content-Type: application/json" --data "{\"name\":\"john\",\"pass\":\"doe\"}" localhost:3000
  20.  
  21. // curl -X POST -H "Content-Type: application/xml" --data "<login><name>john</name><pass>doe</pass></login>" localhost:3000
  22.  
  23. // curl -X POST -H "Content-Type: application/x-www-form-urlencoded" --data "name=john&pass=doe" localhost:3000
  24.  
  25. // curl -X POST -F name=john -F pass=doe http://localhost:3000
  26.  
  27. // curl -X POST "http://localhost:3000/?name=john&pass=doe"