diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index 8a7431792..984e463cf 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -1821,10 +1821,10 @@ func prepareRequest(r *http.Request, repl *caddy.Replacer, w http.ResponseWriter ctx = context.WithValue(ctx, ServerCtxKey, s) trusted, clientIP := determineTrustedProxy(r, s) - ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{ - TrustedProxyVarKey: trusted, - ClientIPVarKey: clientIP, - }) + varsMap := &sync.Map{} + varsMap.Store(TrustedProxyVarKey, trusted) + varsMap.Store(ClientIPVarKey, clientIP) + ctx = context.WithValue(ctx, VarsCtxKey, varsMap) ctx = context.WithValue(ctx, routeGroupCtxKey, make(map[string]struct{})) diff --git a/modules/caddyhttp/vars.go b/modules/caddyhttp/vars.go index cb027faff..803dd7695 100644 --- a/modules/caddyhttp/vars.go +++ b/modules/caddyhttp/vars.go @@ -21,6 +21,7 @@ import ( "net/http" "reflect" "strings" + "sync" "cel.dev/cel-go/cel" "cel.dev/cel-go/common/types/ref" @@ -450,11 +451,12 @@ func (m MatchVarsRE) Validate() error { // GetVar gets a value out of the context's variable table by key. // If the key does not exist, the return value will be nil. func GetVar(ctx context.Context, key string) any { - varMap, ok := ctx.Value(VarsCtxKey).(map[string]any) + varMap, ok := ctx.Value(VarsCtxKey).(*sync.Map) if !ok { return nil } - return varMap[key] + val, _ := varMap.Load(key) + return val } // SetVar sets a value in the context's variable table with @@ -465,17 +467,15 @@ func GetVar(ctx context.Context, key string) any { // underlying value does not count) and the key exists in // the table, the key+value will be deleted from the table. func SetVar(ctx context.Context, key string, value any) { - varMap, ok := ctx.Value(VarsCtxKey).(map[string]any) + varMap, ok := ctx.Value(VarsCtxKey).(*sync.Map) if !ok { return } if value == nil { - if _, ok := varMap[key]; ok { - delete(varMap, key) - return - } + varMap.Delete(key) + return } - varMap[key] = value + varMap.Store(key, value) } // Interface guards