package cors import ( "strconv" "strings" "github.com/gin-gonic/gin" ) type Config struct { AllowOrigins []string AllowMethods []string AllowHeaders []string ExposeHeaders []string AllowCredentials bool MaxAge int } func DefaultConfig() Config { return Config{ AllowOrigins: []string{"*"}, AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, MaxAge: 86400, // 24 hours } } func Cors(config Config) gin.HandlerFunc { return func(c *gin.Context) { origin := c.Request.Header.Get("Origin") // 检查是否允许该来源 allowOrigin := "*" for _, o := range config.AllowOrigins { if o == origin { allowOrigin = origin break } } c.Header("Access-Control-Allow-Origin", allowOrigin) c.Header("Access-Control-Allow-Methods", strings.Join(config.AllowMethods, ",")) c.Header("Access-Control-Allow-Headers", strings.Join(config.AllowHeaders, ",")) c.Header("Access-Control-Expose-Headers", strings.Join(config.ExposeHeaders, ",")) c.Header("Access-Control-Max-Age", strconv.Itoa(config.MaxAge)) if config.AllowCredentials { c.Header("Access-Control-Allow-Credentials", "true") } if c.Request.Method == "OPTIONS" { c.AbortWithStatus(204) return } c.Next() } }