When using gin-contrib/cors middleware directly in the default router, it works perfectly fine for any url, but when I create a group using r.Group(“/api”), the cors does not apply to any of the route in that group.
When checking the response headers, I’ve found that when using group router, the ‘access-control-allow-origin’ is not set. I can still manually set the header and it works, but the cors middleware just seems to not be working at all.
If I just set all my routes on the default router, everything works flawlessly.
I’ve tried to set the middleware to the root router:
func main() {
// other code
r := gin.Default()
r.Use(cors.Default())
apiRouter := r.Group("/api")
apiRouter.GET("/record", func(ctx *gin.Context) {
// other code
})
r.Run("127.0.0.1:3000")
}
To the group router:
func main() {
// other code
r := gin.Default()
apiRouter := r.Group("/api")
apiRouter.Use(cors.Default())
apiRouter.GET("/record", func(ctx *gin.Context) {
// other code
})
r.Run("127.0.0.1:3000")
}
or both, but all of them failed.
It works when the routes are set on the default router:
func main() {
// other code
r := gin.Default()
r.Use(cors.Default())
r.GET("/api/record", func(ctx *gin.Context) {
// other code
})
r.Run("127.0.0.1:3000")
}
(btw, I’ve seen people talked about tailing ‘/’ in group route before, but sadly it is not the cause of this problem)
Zhou Xudong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.