Skip to content

Commit 0ca4249

Browse files
authored
Merge pull request #4368 from gofiber/copilot/optimize-cors-origin-lookup
⚡ perf: Optimize CORS exact-origin lookup to O(1)
2 parents bf86a05 + 928e35d commit 0ca4249

2 files changed

Lines changed: 21 additions & 5 deletions

File tree

middleware/cors/cors.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package cors
22

33
import (
4-
"slices"
54
"strconv"
65
"strings"
76

@@ -53,9 +52,9 @@ func New(config ...Config) fiber.Handler {
5352
log.Warn("[CORS] Both 'AllowOrigins' and 'AllowOriginsFunc' have been defined.")
5453
}
5554

56-
// allowOrigins is a slice of strings that contains the allowed origins
55+
// allowOrigins is a set of strings that contains the allowed origins
5756
// defined in the 'AllowOrigins' configuration.
58-
allowOrigins := []string{}
57+
allowOrigins := make(map[string]struct{}, len(cfg.AllowOrigins))
5958
allowSubOrigins := []subdomain{}
6059

6160
// Validate and normalize static AllowOrigins
@@ -84,7 +83,7 @@ func New(config ...Config) fiber.Handler {
8483
if !isValid {
8584
panic("[CORS] Invalid origin format in configuration: " + maskValue(trimmedOrigin))
8685
}
87-
allowOrigins = append(allowOrigins, normalizedOrigin)
86+
allowOrigins[normalizedOrigin] = struct{}{}
8887
}
8988
}
9089

@@ -141,7 +140,7 @@ func New(config ...Config) fiber.Handler {
141140
allowOrigin = "*"
142141
} else {
143142
// Check if the origin is in the list of allowed origins
144-
if slices.Contains(allowOrigins, originHeader) {
143+
if _, ok := allowOrigins[originHeader]; ok {
145144
allowOrigin = originHeaderRaw
146145
}
147146

middleware/cors/cors_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,23 @@ func Test_CORS_Preserve_Origin_Case(t *testing.T) {
101101
require.Equal(t, origin, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin)))
102102
}
103103

104+
func Test_CORS_AllowOrigins_NormalizedExactLookup(t *testing.T) {
105+
t.Parallel()
106+
107+
app := fiber.New()
108+
app.Use(New(Config{AllowOrigins: []string{" HTTP://EXAMPLE.COM/ "}}))
109+
110+
origin := "http://example.com"
111+
112+
ctx := &fasthttp.RequestCtx{}
113+
ctx.Request.Header.SetMethod(fiber.MethodOptions)
114+
ctx.Request.Header.Set(fiber.HeaderAccessControlRequestMethod, fiber.MethodGet)
115+
ctx.Request.Header.Set(fiber.HeaderOrigin, origin)
116+
app.Handler()(ctx)
117+
118+
require.Equal(t, origin, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin)))
119+
}
120+
104121
func testDefaultOrEmptyConfig(t *testing.T, app *fiber.App) {
105122
t.Helper()
106123

0 commit comments

Comments
 (0)