Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Proposal: Config.MatchPaths #147

Open
klm127 opened this issue Apr 10, 2024 · 1 comment
Open

Feature Proposal: Config.MatchPaths #147

klm127 opened this issue Apr 10, 2024 · 1 comment

Comments

@klm127
Copy link

klm127 commented Apr 10, 2024

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

@jub0bs
Copy link

jub0bs commented Apr 23, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants