CORS request not applying correct on backend
Using the package and can not figure out why corsConfig is not applying to my localhost frontend. Any help will be much appreciated.
func main() {
router := gin.Default()
corsConfig := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"PUT", "PATCH", "GET", "POST", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"*"},
AllowCredentials: false,
MaxAge: int(12 * time.Hour),
})
router.Use(corsConfig)
connDB, err := postgres.InitDB()
if err != nil {
log.Fatal(err)
return
}
defer connDB.Close()
// Our server will live in the routes package
routes.Run()
}
import (
"github.com/gin-gonic/gin"
)
var (
router = gin.Default()
)
// Run will start the server
func Run() {
getRoutes()
router.Run(":8000")
}
// getRoutes will create our routes of our entire application
// this way every group of routes can be defined in their own file
// so this one won't be so messy
func getRoutes() {
v1 := router.Group("/v1")
addUserRoutes(v1)
addPingRoutes(v1)
v2 := router.Group("/v2")
addPingRoutes(v2)
router.GET("/testing", func(c *gin.Context) {
c.JSON(200, "hello")
})
}

Image didn't post correctly.

it seems working for me
➜ curl -D - -H "Origin: google.com" http://localhost:8080/v1/
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Vary: Origin
Date: Fri, 09 Oct 2020 02:05:13 GMT
Content-Length: 7
"hello"
➜ curl -D - -H "Origin: google.com" http://localhost:8080/v2/
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Fri, 09 Oct 2020 02:05:15 GMT
Content-Length: 10
"hello v2"
here is the code
package main
import (
cors "github.com/rs/cors/wrapper/gin"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
corsConfig := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"PUT", "PATCH", "GET", "POST", "DELETE", "OPTIONS"},
AllowCredentials: false,
MaxAge: int(12 * time.Hour),
})
group := router.Group("/v1")
group.Use(corsConfig)
group.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, "hello")
})
group2 := router.Group("/v2")
group2.GET("/", func(context *gin.Context) {
context.JSON(http.StatusOK, "hello v2")
})
router.Run()
}
go.mod
go 1.13
require (
github.com/gin-gonic/gin v1.6.3
github.com/rs/cors v1.7.0
)
Are you using Firefox? There seems to be an issue with pre-flight requests on Firefox.
I was using Google Chrome I found a work around. It was a problem with calling the method inside my Run() function.
for anyone else coming here to look for an answer - I would honestly suggest just using a different language. Java/Javascript have much better designed libraries/frameworks for handling CORS easily.
@rs This one isn't reproducible and could likely be closed.