New creates a new middleware handler
(config ...Config)
| 25 | |
| 26 | // New creates a new middleware handler |
| 27 | func New(config ...Config) fiber.Handler { |
| 28 | // Set default config |
| 29 | cfg := ConfigDefault |
| 30 | |
| 31 | // Override config if provided |
| 32 | if len(config) > 0 { |
| 33 | cfg = config[0] |
| 34 | |
| 35 | // Set default values |
| 36 | if len(cfg.AllowMethods) == 0 { |
| 37 | cfg.AllowMethods = ConfigDefault.AllowMethods |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | redactValues := !cfg.DisableValueRedaction |
| 42 | |
| 43 | maskValue := func(value string) string { |
| 44 | if redactValues { |
| 45 | return redactedValue |
| 46 | } |
| 47 | return value |
| 48 | } |
| 49 | |
| 50 | // Warning logs if both AllowOrigins and AllowOriginsFunc are set |
| 51 | if len(cfg.AllowOrigins) > 0 && cfg.AllowOriginsFunc != nil { |
| 52 | log.Warn("[CORS] Both 'AllowOrigins' and 'AllowOriginsFunc' have been defined.") |
| 53 | } |
| 54 | |
| 55 | // allowOrigins is a set of strings that contains the allowed origins |
| 56 | // defined in the 'AllowOrigins' configuration. |
| 57 | allowOrigins := make(map[string]struct{}, len(cfg.AllowOrigins)) |
| 58 | allowSubOrigins := []subdomain{} |
| 59 | |
| 60 | // Validate and normalize static AllowOrigins |
| 61 | allowAllOrigins := len(cfg.AllowOrigins) == 0 && cfg.AllowOriginsFunc == nil |
| 62 | for _, origin := range cfg.AllowOrigins { |
| 63 | if origin == "*" { |
| 64 | allowAllOrigins = true |
| 65 | break |
| 66 | } |
| 67 | |
| 68 | trimmedOrigin := utils.TrimSpace(origin) |
| 69 | if before, after, found := strings.Cut(trimmedOrigin, "://*."); found { |
| 70 | withoutWildcard := before + "://" + after |
| 71 | isValid, normalizedOrigin := normalizeOrigin(withoutWildcard) |
| 72 | if !isValid { |
| 73 | panic("[CORS] Invalid origin format in configuration: " + maskValue(trimmedOrigin)) |
| 74 | } |
| 75 | scheme, host, ok := strings.Cut(normalizedOrigin, "://") |
| 76 | if !ok { |
| 77 | panic("[CORS] Invalid origin format after normalization:" + maskValue(trimmedOrigin)) |
| 78 | } |
| 79 | sd := subdomain{prefix: scheme + "://", suffix: host} |
| 80 | allowSubOrigins = append(allowSubOrigins, sd) |
| 81 | } else { |
| 82 | isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin) |
| 83 | if !isValid { |
| 84 | panic("[CORS] Invalid origin format in configuration: " + maskValue(trimmedOrigin)) |