diff --git a/cmd/server/main.go b/cmd/server/main.go index 7b9aefe..2af3417 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -114,6 +114,7 @@ func main() { // Gin setup r := gin.New() r.Use(gin.Recovery()) + r.Use(middleware.CORS()) r.Use(middleware.GinLogger()) // Public routes diff --git a/internal/middleware/cors.go b/internal/middleware/cors.go new file mode 100644 index 0000000..481b67b --- /dev/null +++ b/internal/middleware/cors.go @@ -0,0 +1,30 @@ +package middleware + +import ( + "net/http" + "strings" + + "github.com/gin-gonic/gin" +) + +// CORS adds permissive demo CORS headers for any origin. +func CORS() gin.HandlerFunc { + allowedMethods := "GET, POST, PUT, DELETE, OPTIONS" + allowedHeaders := "Authorization, Content-Type" + + return func(c *gin.Context) { + if c.GetHeader("Origin") != "" { + headers := c.Writer.Header() + headers.Set("Access-Control-Allow-Origin", "*") + headers.Set("Access-Control-Allow-Methods", allowedMethods) + headers.Set("Access-Control-Allow-Headers", allowedHeaders) + } + + if strings.EqualFold(c.Request.Method, http.MethodOptions) { + c.AbortWithStatus(http.StatusNoContent) + return + } + + c.Next() + } +}