goext/ctxext/getter.go
Mike Schwörer 361dca5c85
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 2m56s
v0.0.521 ctxext
2024-10-05 01:06:36 +02:00

28 lines
429 B
Go

package ctxext
import "context"
func Value[T any](ctx context.Context, key any) (T, bool) {
v := ctx.Value(key)
if v == nil {
return *new(T), false
}
if tv, ok := v.(T); !ok {
return *new(T), false
} else {
return tv, true
}
}
func ValueOrDefault[T any](ctx context.Context, key any, def T) T {
v := ctx.Value(key)
if v == nil {
return def
}
if tv, ok := v.(T); !ok {
return def
} else {
return tv
}
}