Skip to content

Improve middleware for router groups  #3546

@Murderlon

Description

@Murderlon

Problem

  • When using router groups, .Use does not do anything as middleware needs to be defined before routes. That is fine for global middleware, but doesn't work for groups which is not intention revealing and blocks essential patterns, such as different CORS middleware per group.
  • gin.RouterGroup does not expose the native http.Handler in order to pass it to third-party middleware libraries.
  • Related: grouping routes and middleware not working #531

Consider this example:

group := router.Group("/group")
{
  group.Use(CORS()) // does not work. Chaining it to `Group` above also does not.
  group.POST("/", someHandler())
}

It gets worse when you'd like to use third-party middleware which expects a http.Handler. It would be great if this works:

group := router.Group("/group")
{
  group.Use(gin.wrapH(thirdparty.Middleware(group.Handler()))) // note: group.Handler() doesn't exist
  group.POST("/", someHandler())
}

Instead I have to extract the code from the library into my own project, and if I only want it to apply to a group, we get something like this:

group := router.Group("/group")
{
  group.OPTIONS("/*group", Middleware())
  group.POST("/", Middleware(), someHandler())
  group.HEAD("/:id", Middleware(), someHandler())
  group.PATCH("/:id", Middleware(), someHandler())
  group.DELETE("/:id", Middleware(), someHandler())
  group.GET("/:id", Middleware(), someHandler())
}

Solution

  • Expose http.Handler in gin.RouterGroup
  • Allow .Use to be used inside groups

I'm willing to contribute these changes if we agree on this and I get some tips on how to approach it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions