Description

A question about gin and middleware. If I add a global middleware, using router.Use, after creating a router.Group, it does not execute for any of the Global routes. While debugging, I see the handlers have been added to the router.Group (engine.handlers), but they don’t execute for the endpoints under the Group either.

I am trying to understand if I am using this correctly.

How to reproduce

func (api *API) RegisterPrivateRoutes() {
    privateRoute := api.router.Group(PrivatePrefix)
    //privateRoute.Use(middleware.WithUserID)

    //Routes to Handle
    privateRoute.POST("/users/keys", api.addKey)
}

func (api *API) Handler() http.Handler {
    api.RegisterPrivateRoutes().  //This does not let the below global middleware work for the addKey route
    api.router.Use(middleware.SomeMiddleware)                       
    api.router.Use(middleware.SomeMiddleware2)                  
    api.RegisterPrivateRoutes().  //This lets the middleware work fine
}

Expectations

I would expect that registering the global middleware after registering the route should also work. I couldn't find related documentation mentioning this anywhere, and I couldn't find any documentation on the web.

Environment

  • go version: 1.18
  • gin version (or commit ref):v1.7.7
  • operating system: MacOS

Comment From: Albert-Gao

the rule is simple, global middleware MUST be registered before all routes, you can add your logic before/after the c.Next() to control the pre-stage or post-stage.

For pre-stage, the order is 123 as you register For post-stage, the order is 321 the last registered global middleware gets executed 1st.

Comment From: lavin-ds

Thanks for your helpful response. This cleared it up for me 🎉