Description
How to reproduce
I am sending an AJAX request which has trailing slash redirect but it does not redirects because of CORS issue. I dig the code more and then i found that gin.go
file has redirectRequest
function github.com/gin-gonic/gin/gin.go
if i add the the CORS header then the whole request works fine as you can see the screenshot under EXPECTATION section.
How to resolve the issue without modifying the GIN core file ?
func redirectRequest(c *Context) {
// CODE INSERTED ==================
c.Writer.Header().Set("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
req := c.Request
....
}
Expectations
Actual result
Environment
- go version: 1.14
- gin version (or commit ref): v1.6.3
- operating system: OSX
Comment From: khanakia
Any update ?
Comment From: unbyte
see https://github.com/gin-contrib/cors
Comment From: khanakia
@unbyte i did already test that git contrib cors. CORS are not working for Temporary Redirects that's why i have to add it manually.
Comment From: GiancarlosIO
Same problem here 😢
Comment From: Thytu
same issue, any update?
Comment From: khanakia
@Thytu do not make the request with trailing slash so your request won't be redirected
Comment From: dungmv
any update
Comment From: alirostami1
I use this workaround to remove trailing slash from URL path before even passing it to gin handler
type Router struct {
*gin.Engine
}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// remove trailing slash
if strings.HasSuffix(req.RequestURI, "/") {
req.URL.Path = filepath.Clean(req.URL.Path)
}
r.Engine.ServeHTTP(w, req)
}
func main() {
g := gin.Default()
g.RedirectTrailingSlash = false
g.RedirectFixedPath = false
g.RemoteIPHeaders = append(g.RemoteIPHeaders, "X-Original-Forwarded-For", "Ar-Real-Ip", "CF-Connecting-IP")
g.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
skipContextPathRouter := Router{
Engine: g,
}
server := &http.Server{
Addr: "0.0.0.0:5050",
Handler: &skipContextPathRouter,
}
err := server.ListenAndServe()
if err != nil {
log.Fatalf("server stopped: %v", err)
}
}