🤗 [Question]: Is the Ctx.BodyParser missing in v3?
rolandihms opened this issue · comments
Question Description
Hi Guys,
New to Go/Fiber and really been enjoying it. I have noticed that the BodyParser is missing in the v3 branch. The v3-alpha still includes it and the documentation is still referring to the method.
#https://github.com/gofiber/fiber/blob/v3-alpha/ctx.go#L336
Latest:
#https://github.com/gofiber/fiber/blob/main/ctx.go
Is this correct, are the docs simply outdated?
#https://docs.gofiber.io/api/ctx#bodyparser
Appreciate any feedback,
Thanks
Code Snippet (optional)
package main
import "github.com/gofiber/fiber/v3"
import "log"
func main() {
app := fiber.New()
type payload struct {
Html string `json:"html"`
}
app.Post("/html", func(c fiber.Ctx) error {
body := new(payload)
if err := c.BodyParser(body); err != nil {
return err
}
log.Println("html", body.Html)
return c.Send(c.Body())
})
log.Fatal(app.Listen(":3000"))
}
Checklist:
- I agree to follow Fiber's Code of Conduct.
- I have checked for existing issues that describe my questions prior to opening this one.
- I understand that improperly formatted questions may be closed without explanation.
Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord
Hi @rolandihms, yes I believe the docs are still being updated for v3. c.BodyParser()
was removed in v3 in favor of moving implementation details for binding payloads to a struct and related tasks into a new *fiber.Bind
struct located at fiber/bind.go. You can get a pointer to this struct by using the c.Bind()
defined in fiber/ctx_interface.go.
To upgrade your code snippet to use the new c.Bind()
method, it would look like this:
package main
import (
"github.com/gofiber/fiber/v3"
"log"
)
type payload struct {
Html string `json:"html"`
}
func main() {
app := fiber.New()
app.Post("/html", func(c fiber.Ctx) error {
body := new(payload)
if err := c.Bind().JSON(body); err != nil {
return err
}
log.Println("html", body.Html)
return c.Send(c.Body())
})
log.Fatal(app.Listen(":3000"))
}
Also, did you mean to use return c.Send(body)
instead of return c.Send(c.Body())
? Sending c.Body()
wouldn't require using c.Bind().JSON()
within the POST /html
handler in this example.
I hope this is helpful!
Thanks @grivera64 makes perfect sense thank you.