Open verdverm opened 8 years ago
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.)
In my case, I am using a react app as "source of http calls". I tried to use many of suggestions in this thread, but apparently none of them worked.
Then I looked at the browser network develop tab, when then i realized that react sends an OPTION request, ant at request header there was 'Access-Control-Request-Headers: authorization,content-type,user-agent'
At this moment, i added "user-agent" in the response header "Access-Control-Allow-Headers", and then all worked. The "final" code was:
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With,user-agent")
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