cors.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package middleware
  2. import (
  3. "time"
  4. "github.com/gin-contrib/cors"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // CORSConfig represents the configuration for CORS
  8. type CORSConfig struct {
  9. AllowOrigins []string
  10. AllowCredentials bool
  11. MaxAge time.Duration
  12. TrustedProxies []string
  13. }
  14. // DefaultCORSConfig returns the default CORS configuration
  15. func DefaultCORSConfig() *CORSConfig {
  16. return &CORSConfig{
  17. AllowOrigins: []string{"*"},
  18. AllowCredentials: true,
  19. MaxAge: 12 * time.Hour,
  20. TrustedProxies: []string{"localhost", "127.0.0.1"},
  21. }
  22. }
  23. // CORS returns a middleware for handling CORS with secure defaults
  24. func CORS(cfg *CORSConfig) gin.HandlerFunc {
  25. if cfg == nil {
  26. cfg = DefaultCORSConfig()
  27. }
  28. config := cors.Config{
  29. AllowOrigins: cfg.AllowOrigins,
  30. AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
  31. AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Request-ID"},
  32. ExposeHeaders: []string{"Content-Length", "Content-Type", "X-Request-ID"},
  33. AllowCredentials: cfg.AllowCredentials,
  34. MaxAge: cfg.MaxAge,
  35. }
  36. // Add security-focused CORS settings
  37. config.AllowWildcard = true
  38. config.AllowBrowserExtensions = false
  39. config.AllowWebSockets = false
  40. config.AllowFiles = false
  41. return cors.New(config)
  42. }