Skip to content

grouping routes and middleware not working #531

@rachidify

Description

@rachidify

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")
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions