ctxval

package
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 1 Imported by: 0

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

func NewKey[T any](name string) *Key[T]

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

func (k *Key[T]) Get(ctx context.Context) (T, bool)

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

func (k *Key[T]) GetOr(ctx context.Context, fallback T) T

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

func (k *Key[T]) MustGet(ctx context.Context) T

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.

func (*Key[T]) Name

func (k *Key[T]) Name() string

Name reports the diagnostic name passed to NewKey.

func (*Key[T]) Set

func (k *Key[T]) Set(ctx context.Context, v T) context.Context

Set returns a child context that carries v under k. Storing the zero value of T is legal; callers that want "absent" semantics should use a pointer T and store nil to mean "explicitly cleared".

func (*Key[T]) String

func (k *Key[T]) String() string

String implements fmt.Stringer for friendlier debug output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL