This commit is contained in:
Tomas Dvorak
2026-02-24 10:33:08 +01:00
parent b083dac3f0
commit 55d0284b2a
90 changed files with 27855 additions and 1940 deletions
+63
View File
@@ -0,0 +1,63 @@
package middleware
import (
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
)
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
allowedOrigins := os.Getenv("CORS_ALLOWED_ORIGINS")
ginMode := os.Getenv("GIN_MODE")
if allowedOrigins == "" {
if ginMode == "release" {
c.JSON(http.StatusForbidden, gin.H{
"error": "CORS not configured for production",
"message": "Please set CORS_ALLOWED_ORIGINS environment variable",
})
c.Abort()
return
} else {
allowedOrigins = "http://localhost:5173,http://localhost:3000,http://localhost:8080"
}
}
origin := c.Request.Header.Get("Origin")
allowed := false
if allowedOrigins == "*" {
allowed = true
} else {
for _, allowedOrigin := range strings.Split(allowedOrigins, ",") {
if strings.TrimSpace(allowedOrigin) == origin {
allowed = true
break
}
}
}
if allowed {
if allowedOrigins == "*" {
c.Header("Access-Control-Allow-Origin", "*")
} else {
c.Header("Access-Control-Allow-Origin", origin)
}
}
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Access-Control-Max-Age", "86400")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}