vignesh
vignesh

Reputation: 568

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

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.

Upvotes: 1

Views: 3446

Answers (2)

ashemez
ashemez

Reputation: 120

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()

Upvotes: 3

joelthegraf
joelthegraf

Reputation: 146

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)

Upvotes: 4

Related Questions