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
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:
I thought this could be a candidate for a config feature, something like
Config.MatchPathsof type []stringCould I do a PR for this feature?
Thanks