https://github.com/julienschmidt/httprouter now supports OPTIONS response generation by a boolean flag
The code paths for routing still seem quite close. Can we bring this enhancement into the Gin router?
Relevant code:
https://github.com/julienschmidt/httprouter/blob/master/router.go#L379
https://github.com/julienschmidt/httprouter/blob/master/router.go#L296
This may be a moot point if #498 (fasthttprouter) is accepted
This is implemented with my comments on #155
Yes! About a year ago I discovered the article that httprouter links to in their readme. I think OPTIONS is great for testing purposes as I can have a generic integration test that uses OPTIONS to crawl all possible combinations!
The downside is writing lots of specific code that has to be changed when the api surface changes would be a terrible mistake.
A way to fix this issue quickly. Try to create new middleware:
func Options(c *gin.Context) {
if c.Request.Method != "OPTIONS" {
c.Next()
} else {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Content-Type", "application/json")
c.AbortWithStatus(http.StatusOK)
}
}
in router:
e.Use(header.Options)
For anyone who meet CORS problem. Just FYI. The above code doesn't work for me somehow. I don't know why. This middleware https://github.com/gin-contrib/cors works for me (recommended by @Depado).
an edit at @appleboy 's options function
func Options(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Access-Control-Allow-Headers", "authorization, origin, content-type, accept")
c.Header("Allow", "HEAD,GET,POST,PUT,PATCH,DELETE,OPTIONS")
c.Header("Content-Type", "application/json")
if c.Request.Method != "OPTIONS" {
c.Next()
} else {
c.AbortWithStatus(http.StatusOK)
}
}
on using this function as a middleware it solves CORS issue and also responds with the CORS header on any options route(Note: turn it off for production if not using it.)
Most helpful comment
A way to fix this issue quickly. Try to create new middleware:
in router: