How to add different middleware to routes under same sub route in gofiber

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

How to add different middleware to routes under same sub route in 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)

现在我有两个不同的中间件。我需要在子路由1、2、3上使用middleware_1,在子路由4、5上使用middleware_2。最佳的语法是什么?我找到的解决方案是在每个路由中使用app.Use("/path", middleware)方法并显式声明中间件。这是唯一的解决方案吗?还有更简洁的方法吗?

英文:

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.

答案1

得分: 2

你可以这样做:

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)

答案2

得分: 2

你需要在中间件方法中使用return ctx.Next(),以便让请求通过路由中的多个方法。

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

假设你的handler2需要执行并转到handler3,然后再转到handler4。

你可以在每个handler中实现一些检查逻辑。如果满足条件时需要进入下一个handler,只需运行return 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()

huangapple
  • 本文由 发表于 2022年6月16日 20:22:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/72645801.html
匿名

发表评论

匿名网友

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

确定