Compare commits

...

1 commit

Author SHA1 Message Date
Mohammed Al Sahaf
2aca49d5f6
http: use sync.Map for request-scoped vars
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
2026-03-26 19:50:33 +03:00
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) ctx = context.WithValue(ctx, ServerCtxKey, s)
trusted, clientIP := determineTrustedProxy(r, s) trusted, clientIP := determineTrustedProxy(r, s)
ctx = context.WithValue(ctx, VarsCtxKey, map[string]any{ varsMap := &sync.Map{}
TrustedProxyVarKey: trusted, varsMap.Store(TrustedProxyVarKey, trusted)
ClientIPVarKey: clientIP, varsMap.Store(ClientIPVarKey, clientIP)
}) ctx = context.WithValue(ctx, VarsCtxKey, varsMap)
ctx = context.WithValue(ctx, routeGroupCtxKey, make(map[string]struct{})) ctx = context.WithValue(ctx, routeGroupCtxKey, make(map[string]struct{}))

View file

@ -20,6 +20,7 @@ import (
"net/http" "net/http"
"reflect" "reflect"
"strings" "strings"
"sync"
"github.com/google/cel-go/cel" "github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types/ref" "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. // 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. // If the key does not exist, the return value will be nil.
func GetVar(ctx context.Context, key string) any { 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 { if !ok {
return nil return nil
} }
return varMap[key] val, _ := varMap.Load(key)
return val
} }
// SetVar sets a value in the context's variable table with // 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 // underlying value does not count) and the key exists in
// the table, the key+value will be deleted from the table. // the table, the key+value will be deleted from the table.
func SetVar(ctx context.Context, key string, value any) { 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 { if !ok {
return return
} }
if value == nil { if value == nil {
if _, ok := varMap[key]; ok { varMap.Delete(key)
delete(varMap, key) return
return
}
} }
varMap[key] = value varMap.Store(key, value)
} }
// Interface guards // Interface guards