Home > Software design >  Automatically parse the body?
Automatically parse the body?

Time:06-20

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!

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related