如何在Gofiber的同一子路线下向路线添加不同的中间件

发布于 2025-02-07 22:14:50 字数 444 浏览 2 评论 0原文

我在下面有一个路线配置,并带有基本路线,现在有5个子分量

baseRoute := app.Group("/base")
baseRoute.Post("/sub_route1", handler1)
baseRoute.Post("/sub_route2", handler2)
baseRoute.Post("/sub_route3", handler3)
baseRoute.Post("/sub_route4", handler4)
baseRoute.Post("/sub_route5", handler5)

,现在我有两种不同的中间。我需要在子流量4、5上的子流程1、2、3和Middleware_2上使用Middleware_1。什么是最佳的语法。我提到的解决方案是使用app.use(“/path”,中间件)方法,并明确声明每条路线中的中间地点。是唯一的解决方案,或者我们有一种更清洁的方法。

I have a route configuration as below with a base route and 5 subroutes under that

baseRoute := app.Group("/base")
baseRoute.Post("/sub_route1", handler1)
baseRoute.Post("/sub_route2", handler2)
baseRoute.Post("/sub_route3", handler3)
baseRoute.Post("/sub_route4", handler4)
baseRoute.Post("/sub_route5", handler5)

now i have two different middlewares. I need to use middleware_1 on subroutes 1, 2, 3 and middleware_2 on subroutes 4, 5. What is the best syntax to do this. The solution that i came accross was to use app.Use("/path", middleware) method and explicitly declare the middlewares in each route. Is that the only solution or we have a cleaner way of doing it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

够运 2025-02-14 22:14:50

您可以做这样的事情:

baseRoute := app.Group("/base")
usesM1 := baseRoute.Group("/", middleware1)
usesM1.Post("/sub_route1", handler1)
usesM1.Post("/sub_route2", handler2)
usesM1.Post("/sub_route3", handler3)
usesM2 := baseRoute.Group("/", middleware2)
usesM2.Post("/sub_route4", handler4)
usesM2.Post("/sub_route5", handler5)

You could do something like that:

baseRoute := app.Group("/base")
usesM1 := baseRoute.Group("/", middleware1)
usesM1.Post("/sub_route1", handler1)
usesM1.Post("/sub_route2", handler2)
usesM1.Post("/sub_route3", handler3)
usesM2 := baseRoute.Group("/", middleware2)
usesM2.Post("/sub_route4", handler4)
usesM2.Post("/sub_route5", handler5)
痕至 2025-02-14 22:14:50

您需要的是在中间件方法中使用返回ctx.next(),以使其通过路由中的多种方法。

baseroute.post(“/some_route”,handler1,handler2,handler3,handler4)

假设您有handler2需要执行并移至handler3,然后移动到handler3和该handler4之后。

您实现代码在每个处理程序中进行一些检查。如果经过处理时需要使用处理程序,则在满足条件时只需运行此返回ctx.next()

What you need is to use return ctx.Next() in the middleware methods to let it go through multiple methods in a route.

baseRoute.Post("/some_route", handler1, handler2, handler3, handler4)

Let's say you have handler2 needs to perform and move to handler3 and after that handler4.

You implement your code do some checks in each handler. If a handler needs to go to the next handler when the condition is met just run this return ctx.Next()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文