Documentation
¶
Overview ¶
Package ctxval is a type-safe wrapper over context.Context values using generics. A Key[T] is a strongly-typed, package-private context key bound to a value type T; callers get compile-time guarantees that they cannot stash an int under a "*Metadata" key or vice versa, and they cannot collide with another package's keys because each Key is a distinct address.
Typical use:
var metaKey = ctxval.NewKey[*Metadata]("awsmeta")
func Set(ctx context.Context, m *Metadata) context.Context {
return metaKey.Set(ctx, m)
}
func Get(ctx context.Context) (*Metadata, bool) {
return metaKey.Get(ctx)
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Key ¶
type Key[T any] struct { // contains filtered or unexported fields }
Key is a strongly-typed context key bound to value type T. Two Key instances are distinct iff they were created by separate calls to NewKey — the name is for diagnostics and does not affect identity.
func NewKey ¶
NewKey returns a fresh Key[T]. Each call produces a unique key by address; the name is used only for the String method and error messages.
func (*Key[T]) Get ¶
Get returns the value carried under k and true, or the zero value of T and false when no value is present. Callers that prefer a single-value API can wrap this with a fallback helper (see GetOr).
func (*Key[T]) GetOr ¶
GetOr returns the value carried under k, or fallback if none is present. Useful when callers want a single-value API.
func (*Key[T]) MustGet ¶
MustGet returns the value carried under k or panics with a descriptive message when none is present. Use only in code paths where the caller has guaranteed (via middleware or a test setup) that the value will be set.