Hi, I'm having a problem trying to define different middleware for different routes, please let me know if my understanding is correct and whether this behaviour is supported by the framework
Here it's mentioned that to use a middleware, application need to call Engine.Use(middleware)
, which in turns call engine.RouterGroup.Use(middleware)
https://pkg.go.dev/github.com/gin-gonic/gin#Engine.Use
Here it's mentioned that application can define a group of routes that shares common middleware - which is what I want https://pkg.go.dev/github.com/gin-gonic/gin#RouterGroup.Group
However the engine is only attached to one RouterGroup
, so not sure how to define multiple RouterGroup
s for an engine (and whether it's actually supported)
https://pkg.go.dev/github.com/gin-gonic/gin#Engine
Here it's mentioned that once Run
, the engine will block the goroutine, so not sure if it's possible to define multiple engine, one per router group (and whether it's recommended to do so)
https://pkg.go.dev/github.com/gin-gonic/gin#Engine.Run
Comment From: cp-sumi-k
Hello @captainviet, If I understood your question correctly, here is the solution.
Define RouterGroup Like ,
r := gin.Default()
Then apply middleware as per requirement on this routergroup like,
rg1 := r.Group("/group1", middleware1())
rg2 := r.Group("/group2", middleware2())
then use different routes like,
rg1.GET("/", handler1)
rg2.GET("/", handler2)
Comment From: yeqown
As a supplement, you can add middlewares on a handler directly:
g.GET("/path", middleware1, middleware2, handler)
https://github.com/gin-gonic/gin/blob/b01605bb5b43dbf33781970af5ad6633e5549fd1/routergroup.go#L71-L77 https://github.com/gin-gonic/gin/blob/b01605bb5b43dbf33781970af5ad6633e5549fd1/routergroup.go#L209-L220
Comment From: captainviet
Hi @cp-sumi-k , thanks for your suggestion, let us try it out!
thanks @yeqown for the suggestion also!
Comment From: spiropoulos94
Another way of applying middlewares to grouped routes is the following :
testGroup := router.Group("/test").Use(middleWare())
testGroup.GET("/a", controllers.Testa)
testGroup.GET("/b", controllers.Testb)
testGroup.GET("/c", controllers.Testc)
Comment From: gokul1630
I just tried the below one, works fine for each route handler:
func YourCustomMiddleWare(context *gin.Context){
context.AbortWithStatusJSON(404, map[string]string{"message": "route not found"})
}
r.GET("/fetch-data", YourCustomMiddleWare, controllers.YourFunc)