自动解析正文?

huangapple go评论81阅读模式
英文:

Automatically parse the body?

问题

有没有办法自动解析请求的主体,而不是在每个处理程序中都使用这个 if 语句!

我正在使用 go-fiber 框架

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

我听说有些人不推荐这样做,但我很好奇为什么!

英文:

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!

答案1

得分: 2

如果你想创建一个中间件,可以使用以下方法:

const PostKey = "post"

func CreateBodyParsingMiddleware(handler func(*fiber.Ctx) error) func(c *fiber.Ctx) error {
	return func(c *fiber.Ctx) error {
		var post Post // Post 类型在其他地方声明
		if err := c.BodyParser(&post); err != nil {
			return fiber.NewError(fiber.StatusBadRequest, "无效的请求体")
		}
		c.Locals(PostKey, post)
		err := handler(c)
		return err
	}
}

使用类似以下方式的中间件:

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

现在你可以在 myRequestHandler 中使用 c.Locals(PostKey) 来访问 post。

英文:

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.

huangapple
  • 本文由 发表于 2022年6月19日 23:02:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/72677947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定