I am trying to add this middleware

func CORS () gin.HandlerFunc {
    return func(context *gin.Context) {
        context.Writer.Header().Add("Access-Control-Allow-Origin", "*")
        context.Writer.Header().Set("Access-Control-Max-Age", "86400")
        context.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        context.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
        context.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
        context.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

        if context.Request.Method == "OPTIONS" {
            context.AbortWithStatus(200)
        } else {
            context.Next()
        }
    }
}

but not work with grouping routes

  func main () {
    router := gin.New()
    router.Use(CORS())

    // cors middleware not working
    users := router.Group("/users")
    users.GET("/", Users)

    // cors middleware not working
    users := router.Group("/users")
    users.Use(CORS())
    users.GET("/", Users)

    // cors middleware working fine
    router.GET("/users")

    router.Run(":3000")
  }

Comment From: Norbell

Interesting. I used the following main-function and everything works fine.

What part of your code is not working?

  func main () {
    router := gin.New()
    router.Use(CORS())

    users := router.Group("/users")
    users.GET("/", Users)

    router.Run(":3000")
  }

Comment From: douglarek

@rasheedhamdawi is this resolved ? anything share ?

Comment From: sonemaro

@douglarek I had exactly this problem. You should define your middlewares before your grouping route(maybe right after creating the router instance)

Comment From: bkda

Same issue, and you should put your middleware before the routes, like this, and it works.

    r := gin.Default()
    r.Use(Authentication())
    r.POST("/v2/create", handlers.CreateHandler)

Comment From: sonemaro

And here it is what I'm using:

transaction := api.Group("/transaction", HandleApiKey())

transaction.GET("/", func(c *gin.Context) {
    //a nice logic will be here
})

func HandleApiKey() gin.HandlerFunc {
    return func(c *gin.Context) {
    //another nice middleware will be here
    }
}

Comment From: jmwohl

Why is this closed? As far as I can tell, this is still an issue. Or are we not meant to use middleware on router groups?

Comment From: sonemaro

@jmwohl Can I see the code you are using? Have you defined the middleware before the group route?

Comment From: John-Ciuchea

If I define your route like this users.GET("/", Users) in api call you I added a leading slash fetch("http://localhost:3000/users/")

I defined the route without leading slash users.GET("", Users) then I get a cors error when I add the leading slash in api request.

I don't think that cors should have anything to do with leading slashes.

Comment From: liuggio

This is an issue! Is impossible to add middleware to Groups

Comment From: liuggio

Found the problem it's related to gin-contrib/Cors is mandatory to add the options route on subgroup

Comment From: dan-j

Apologies for awaking an old issue, but I've just come across this and also think it's an issue. We have particular aspects of an API which we want open to CORS but not all endpoints.

It looks like middlewares on RouterGroup only execute if a defined route is matched, whereas middlewares on Engine are executed regardless.

Is this something the contributors would be willing to accept if a PR is made?

Comment From: spiropoulos94

Try this :

router := gin.Default()
api := router.Group("/api").Use(middleWareFunc())

Comment From: MikyChow

I had the same issues now.

Comment From: Malik99-rapido

I guess this is a serious issue even I am not being able to use the middleware function in a very trivial code which i wrote. please refer this example: -

func Authenticate() gin.HandlerFunc { fmt.Println("over here : ") return func(ctx *gin.Context) { headerKey := ctx.Request.Header.Get("userId") if len(headerKey) >= 0 { ctx.Next() } else { ctx.Abort() ctx.JSON( http.StatusUnauthorized, "not auth", ) } } }

router := gin.Default() // 1 try with this method router.POST("/api/some/endpoint",Authenticate() ,h.apiHnadler) // 2 try with this method router.POST("/api/some/endpoint" ,h.apiHnadler).Use(Authenticate()) // 3 try with this method router.POST("/api/some/endpoint",Authenticate() ,h.apiHnadler)

I have tried with all the above 3 methods but the middleware function never get called. The problem is that it never calls the middleware function and every time calls the handler function.

details: - go version: 1.14 gin: github.com/gin-gonic/gin v1.6.3

Comment From: madhukar93

Bumping this, issue still exists with v1.9.1

Comment From: candiepih

I had this issue with routes grouping and was able to solve it by adding the middleware immediately after creating the instance

router := gin.Default()

// add middleware here
router.Use(MyMiddleware())

api := router.Group("/api")

Comment From: jub0bs

Related: https://github.com/gin-contrib/cors/issues/35

Comment From: williambao

@sonemaro you safed me, it's fucking wasted me 2 days to debugging, and just because I put the cors middleware to the grouping router like below...

router := e.Default()
api := router.Group("/api", 
    cors.New(cors.Config{.....})
)

When I was put cors middleware outside grouping route, it's works fine...

router := e.Default()
router.Use(   cors.New(cors.Config{.....}))
api := router.Group("/api")

Comment From: Disorrder

There's still an issue!

Comment From: JimChenWYU

There's still an issue!

How to reproduce? it works for me.

Comment From: QingShan-Xu

It is possible to Use Cros middleware immediately after gin routing instantiation.