mirror of
https://github.com/caddyserver/caddy.git
synced 2026-04-23 16:40:44 -04:00
http: use sync.Map for request-scoped vars
Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
This commit is contained in:
@@ -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{}))
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user