From f0bd5da6441d0fc0bd1149718515bc210c82c4db Mon Sep 17 00:00:00 2001 From: Kai Date: Thu, 30 May 2024 21:58:20 +0200 Subject: [PATCH 1/2] middleware to set cors policy in response header --- api/cmd/main.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/api/cmd/main.go b/api/cmd/main.go index ca09e0d..4c5c8a7 100644 --- a/api/cmd/main.go +++ b/api/cmd/main.go @@ -30,13 +30,13 @@ func setupRouter(db *sql.DB) *gin.Engine { }) //Upload a game - r.POST("/games/", gamesController.UploadGame) + r.POST("/games/", CorsHeader, gamesController.UploadGame) //Get all uploaded games - r.GET("/games", gamesController.GetAllGames) + r.GET("/games/", CorsHeader, gamesController.GetAllGames) //Get a specific game by its id - r.GET("/games/:id", gamesController.GetGameById) + r.GET("/games/:id", CorsHeader, gamesController.GetGameById) //Delete a specific game, identified by its id - r.DELETE("/games/:id", gamesController.DeleteGameById) + r.DELETE("/games/:id", CorsHeader, gamesController.DeleteGameById) return r } @@ -85,3 +85,17 @@ func main() { log.Fatal(err.Error()) } } + +func CorsHeader(c *gin.Context) { + c.Writer.Header().Set("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) + c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") + c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") + c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT") + + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + + c.Next() +} From 73d5bdd2c4ed283d37be001fc9cf3c727015770f Mon Sep 17 00:00:00 2001 From: Kai Date: Thu, 30 May 2024 22:23:59 +0200 Subject: [PATCH 2/2] Access-Control-Allow-Origin * --- api/cmd/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/cmd/main.go b/api/cmd/main.go index 4c5c8a7..cacf756 100644 --- a/api/cmd/main.go +++ b/api/cmd/main.go @@ -87,7 +87,7 @@ func main() { } func CorsHeader(c *gin.Context) { - c.Writer.Header().Set("Access-Control-Allow-Origin", c.Request.Header.Get("Origin")) + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")