fix: prevent data races from shared header value slices
Fixes #198
Problem
Package-level slice variables (headerVaryOrigin, headerOriginAll, headerTrue) and struct field slices (preflightVary, exposedHeaders, maxAge) are assigned directly to http.Header maps. Since http.Header values are []string, downstream handlers can mutate the backing array (e.g., via append, slices.Sort, or direct index writes), causing data races when the middleware serves concurrent requests.
Fix
- Replace package-level
varslice declarations withconststring values - Create fresh
[]string{...}literals at each assignment site, so each request gets its own backing array - Apply the same treatment to struct field slices (
preflightVary,exposedHeaders,maxAge)
This eliminates the shared mutable state while keeping the same observable behavior. The allocation cost is negligible — one small slice per CORS header per request.
Testing
All existing tests pass, including with -race.
@Yanhu007 See https://github.com/rs/cors/pull/199, which also aims at fixing #198.
append would be thread safe since the slices are at capacity. Sorting or setting headers by index is unrealistic use cases.
@Yanhu007 did you trigger this bug in your own code?