gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.84k stars 8.02k forks source link

How to use different middleware for different routes #2612

Open captainviet opened 3 years ago

captainviet commented 3 years ago

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 RouterGroups 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

cp-sumi-k commented 3 years ago

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)
yeqown commented 3 years ago

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

captainviet commented 3 years ago

Hi @cp-sumi-k , thanks for your suggestion, let us try it out!

thanks @yeqown for the suggestion also!

spiropoulos94 commented 2 years ago

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)
gokul1630 commented 11 months ago

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)