cors icon indicating copy to clipboard operation
cors copied to clipboard

Feature Proposal: Config.MatchPaths

Open klm127 opened this issue 1 year ago • 1 comments

In a recent project, I wanted to apply CORs headers on just one one path.

I couldn't achieve my objective by adding cors middleware to a gin.RouterGroup, because I had other important, cookie-reading, global middleware I wanted to add to every request, that would run before cors.

I used something like this and used it as the first middleware on the gin.Engine:

// CORS needs to be the first middleware called for endpoints that enable it. This middleware allows specifying which paths have CORs enabled. CORS headers will be set for those paths.
func CORSFor(match_paths []string) gin.HandlerFunc {

	corsHandler := cors.New(cors.Config{
		AllowMethods:           []string{"POST", "GET", "PUT", "PATCH", "DELETE"},
		AllowHeaders:           []string{"Origin", "Cookie", arg.Config.LicenseHeader()},
		AllowCredentials:       true,
		AllowBrowserExtensions: true,
		AllowOriginFunc: func(origin string) bool {
			return true
		},
		MaxAge: 24 * time.Hour,
	})

	return func(c *gin.Context) {
		path := c.Request.URL.Path
		for _, pref := range match_paths {
			if strings.HasPrefix(path, pref) {
                                corsHandler(c)
                                return
			}
		}
		c.Next()
	}
}

I thought this could be a candidate for a config feature, something like Config.MatchPaths of type []string

Could I do a PR for this feature?

Thanks

klm127 avatar Apr 10 '24 02:04 klm127

The problem with such a feature is that it promotes poor separation of concerns: you would then have to worry about routes both at the router level and in the configuration of your CORS middleware.

A better solution, in my opinion, would be to fix Gin so that CORS middleware can be applied to groups.

jub0bs avatar Apr 23 '24 17:04 jub0bs