From ccea48a15a1a95647ac67fc47f9d380de9150edf Mon Sep 17 00:00:00 2001 From: Mohammed JBILOU <95973236+Molaryy@users.noreply.github.com> Date: Sun, 19 Nov 2023 22:52:42 +0100 Subject: [PATCH] feat: added CORS middleware --- backend/middlewares/cors.go | 19 +++++++++++++++++++ backend/router.go | 1 + 2 files changed, 20 insertions(+) create mode 100644 backend/middlewares/cors.go diff --git a/backend/middlewares/cors.go b/backend/middlewares/cors.go new file mode 100644 index 0000000..0e6d7d3 --- /dev/null +++ b/backend/middlewares/cors.go @@ -0,0 +1,19 @@ +package middlewares + +import "github.com/gin-gonic/gin" + +func CORSMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + 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") + + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + + c.Next() + } +} diff --git a/backend/router.go b/backend/router.go index 7b2c327..54cf8fc 100644 --- a/backend/router.go +++ b/backend/router.go @@ -29,6 +29,7 @@ func authHandler(r *gin.Engine) { } func router(r *gin.Engine) { + r.Use(middlewares.CORSMiddleware()) authHandler(r) todosHandler(r) r.NoRoute(RouteNotFound)