Mike Schwörer
361dca5c85
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 2m56s
28 lines
429 B
Go
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
|
|
}
|
|
}
|