Skip to content

Commit

Permalink
chore: refactor validate and normalize
Browse files Browse the repository at this point in the history
  • Loading branch information
sixcolors committed Feb 27, 2024
1 parent 000c548 commit b3c7a2c
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions middleware/cors/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,24 +114,28 @@ func New(config ...Config) fiber.Handler {
}

// allowOrigins is a slice of strings that contains the allowed origins
// that are defined in the 'AllowOrigins' configuration.
// defined in the 'AllowOrigins' configuration.
var allowOrigins []string

// Validate and normalize static AllowOrigins
if cfg.AllowOrigins != "" && cfg.AllowOrigins != "*" {
for _, origin := range strings.Split(cfg.AllowOrigins, ",") {
origin = strings.TrimSpace(origin)
isValid, normalizedOrigin := normalizeOrigin(origin)
origins := strings.Split(cfg.AllowOrigins, ",")
allowOrigins = make([]string, len(origins))

for i, origin := range origins {
trimmedOrigin := strings.TrimSpace(origin)
isValid, normalizedOrigin := normalizeOrigin(trimmedOrigin)

if isValid {
allowOrigins = append(allowOrigins, normalizedOrigin)
allowOrigins[i] = normalizedOrigin
} else {
log.Warnf("[CORS] Invalid origin format in configuration: %s", origin)
log.Warnf("[CORS] Invalid origin format in configuration: %s", trimmedOrigin)
panic("[CORS] Invalid origin provided in configuration")
}
}
} else {
// If AllowOrigins is set to a wildcard or not set,
// set the allowOrigins to a slice with a single element
// set allowOrigins to a slice with a single element
allowOrigins = []string{cfg.AllowOrigins}
}

Expand Down

0 comments on commit b3c7a2c

Please sign in to comment.