Automatically parse the body?

Issue

Is there any way to parse the body of the request automatically, instead of doing this if in each handler!

I’m using the go-fiber framework

if err := c.BodyParser(&post); err != nil {
    // do something
}

I’ve heard that some people don’t recommend this but I’m curious why!

Solution

If you want to create a middleware, use a method like this one:


const PostKey = "post"

func CreateBodyParsingMiddleware(handler func(*fiber.Ctx) error) func(c *fiber.Ctx) error {
    return func(c *fiber.Ctx) error {
        var post Post //type Post is declared elsewhere
        if err := c.BodyParser(&post); err != nil {
            return fiber.NewError(fiber.StatusBadRequest, "invalid body")
        }
        c.Locals(PostKey, post)
        err := handler(c)
        return err
    }
}

Use the middleware with something like

router.Get("/", CreateBodyParsingMiddleware(myRequestHandler))

You can now access the post with c.Locals(PostKey) in myRequestHandler.

Answered By – NotX

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.