1234567891011121314151617181920212223242526272829303132333435 |
- package contextkey
- import (
- "context"
- )
- type CtxKey[T any] struct {
- key any
- }
- func NewCtxKey[T any]() CtxKey[T] {
- type uniqueKey struct{}
- return CtxKey[T]{key: uniqueKey{}}
- }
- func (k CtxKey[T]) WithValue(ctx context.Context, value T) context.Context {
-
- return context.WithValue(ctx, k.key, value)
- }
- func (k CtxKey[T]) GetValue(ctx context.Context) (T, bool) {
-
- v := ctx.Value(k.key)
- if v == nil {
- var zero T
- return zero, false
- }
-
- t, ok := v.(T)
- return t, ok
- }
|