http: use sync.Map for request-scoped vars

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
This commit is contained in:
Mohammed Al Sahaf
2026-03-26 19:50:33 +03:00
parent e98ed6232d
commit 2aca49d5f6
2 changed files with 12 additions and 12 deletions

View File

@@ -935,10 +935,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{}))

View File

@@ -20,6 +20,7 @@ import (
"net/http"
"reflect"
"strings"
"sync"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types/ref"
@@ -443,11 +444,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
@@ -458,17 +460,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