package middleware import ( "time" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) // CORSConfig represents the configuration for CORS type CORSConfig struct { AllowOrigins []string AllowCredentials bool MaxAge time.Duration TrustedProxies []string } // DefaultCORSConfig returns the default CORS configuration func DefaultCORSConfig() *CORSConfig { return &CORSConfig{ AllowOrigins: []string{"*"}, AllowCredentials: true, MaxAge: 12 * time.Hour, TrustedProxies: []string{"localhost", "127.0.0.1"}, } } // CORS returns a middleware for handling CORS with secure defaults func CORS(cfg *CORSConfig) gin.HandlerFunc { if cfg == nil { cfg = DefaultCORSConfig() } config := cors.Config{ AllowOrigins: cfg.AllowOrigins, AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Request-ID"}, ExposeHeaders: []string{"Content-Length", "Content-Type", "X-Request-ID"}, AllowCredentials: cfg.AllowCredentials, MaxAge: cfg.MaxAge, } // Add security-focused CORS settings config.AllowWildcard = true config.AllowBrowserExtensions = false config.AllowWebSockets = false config.AllowFiles = false return cors.New(config) }