如何在Gofiber的同一子路线下向路线添加不同的中间件
我在下面有一个路线配置,并带有基本路线,现在有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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以做这样的事情:
You could do something like that:
您需要的是在中间件方法中使用
返回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()