package middleware import ( "github.com/gin-gonic/gin" ) // CORS middleware pour gérer les en-têtes CORS avec whitelist d'origins configurable // allowedOrigins: liste des origines autorisées (ex: []string{"http://localhost:3000", "https://example.com"}) // Si "*" est dans la liste, toutes les origines sont autorisées func CORS(allowedOrigins []string) gin.HandlerFunc { return func(c *gin.Context) { origin := c.GetHeader("Origin") // Vérifier si l'origine est autorisée if isAllowedOrigin(origin, allowedOrigins) { c.Header("Access-Control-Allow-Origin", origin) } c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") c.Header("Access-Control-Allow-Headers", "Authorization, Content-Type") c.Header("Access-Control-Allow-Credentials", "true") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(204) return } c.Next() } } // isAllowedOrigin vérifie si une origine est dans la liste des origines autorisées func isAllowedOrigin(origin string, allowed []string) bool { for _, o := range allowed { // Permettre toutes les origines si "*" est dans la liste if o == "*" || o == origin { return true } } return false } // CORSDefault crée un middleware CORS avec une whitelist par défaut // Utile pour compatibilité avec le code existant func CORSDefault() gin.HandlerFunc { return CORS([]string{"*"}) }