Closed samber closed 5 months ago
Any luck @samber ?
@samber I am also facing the same issue.
I think cors runs first, when the connection is established, and does not know anything about the endpoint itself ("1/*") so it cannot be used at the Group granularity level.
I had to add an options
mapping to each endpoint
web browser will send OPTIONS
to check CORS policy before request. In common secranio. router only define specific method like get
, post
. SO when server recieve options
method. It will reconginze this route is not registed. then code run into default middleware
// Use attaches a global middleware to the router. ie. the middleware attached though Use() will be
// included in the handlers chain for every single request. Even 404, 405, static files...
// For example, this is the right place for a logger or error management middleware.
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
engine.RouterGroup.Use(middleware...)
engine.rebuild404Handlers()
engine.rebuild405Handlers()
return engine
}
use cors middlware
in default group
!!!
The root cause of this issue lies in Gin's router, not in rs/cors. See https://github.com/gin-gonic/gin/issues/531.
@rs I think you could close this issue.
As the preflight OPTIONS request cannot reach the routergroup's handler chain if there is no valid handler for this OPTIONS request, I use a wrapper to make sure every GET/POST has a paired OPTIONS handler. Then I can give every group different CORS policies.
v1 := r.Group("/api/v1")
v1.Use(cors.New(cors.Config{...}))
addHandler(pri, "POST", "/updateWord", controller.UpdateWord)
pp := r.Group("/api/ext")
pp.Use(cors.New(cors.Config{...}))
addHandler(pri, "GET", "/getAllWords", controller.ListAllWordsForUser)
func addHandler(r *gin.RouterGroup, method string, path string, handler func(c *gin.Context)) {
if method != "OPTIONS" {
r.Handle(method, path, handler)
r.OPTIONS(path, func(c *gin.Context) {})
}else{
r.OPTIONS(path, handler)
}
}
@seerhut method != "OPTIONS"
is too restrictive: not all OPTIONS
requests are preflight requests; see https://jub0bs.com/posts/2023-02-08-fearless-cors/#4-categorise-requests-correctly
@seerhut
method != "OPTIONS"
is too restrictive: not allOPTIONS
requests are preflight requests; see https://jub0bs.com/posts/2023-02-08-fearless-cors/#4-categorise-requests-correctly
Thx, great article for summary!
I need different CORS settings in 2 groups. This middleware works only at "router" level.
The issue can be reproduced with the following code:
Adding the "OPTIONS" catch-all route doesn't change anything.
You can test it with this client.
Any idea how to solve this?