Problem
File: middleware/cors/cors.go:144
The CORS middleware uses slices.Contains(allowOrigins, originHeader) which performs an O(n) linear scan over the configured allowed origins list. This runs on every CORS request (every request with an Origin header).
if slices.Contains(allowOrigins, originHeader) {
allowOrigin = originHeaderRaw
}
Impact
- O(n) per request where n = number of configured origins.
- With many allowed origins (common in multi-tenant SaaS), this becomes a measurable per-request cost.
- The origin matching also iterates
allowSubOrigins linearly (line 150-155).
Proposed fix
Convert allowOrigins from []string to map[string]struct{} at middleware creation time:
allowOriginSet := make(map[string]struct{}, len(cfg.AllowOrigins))
for _, origin := range cfg.AllowOrigins {
// ... normalize ...
allowOriginSet[normalizedOrigin] = struct{}{}
}
// In handler:
if _, ok := allowOriginSet[originHeader]; ok {
allowOrigin = originHeaderRaw
}
This changes lookup from O(n) to O(1). The allowSubOrigins linear scan is harder to optimize but is typically small.
Priority
P1 — Simple fix, measurable improvement for apps with many configured origins.
Identified during a full performance architecture review of the Fiber codebase.
Problem
File:
middleware/cors/cors.go:144The CORS middleware uses
slices.Contains(allowOrigins, originHeader)which performs an O(n) linear scan over the configured allowed origins list. This runs on every CORS request (every request with anOriginheader).Impact
allowSubOriginslinearly (line 150-155).Proposed fix
Convert
allowOriginsfrom[]stringtomap[string]struct{}at middleware creation time:This changes lookup from O(n) to O(1). The
allowSubOriginslinear scan is harder to optimize but is typically small.Priority
P1 — Simple fix, measurable improvement for apps with many configured origins.
Identified during a full performance architecture review of the Fiber codebase.