Documentation ¶
Overview ¶
ctxkey provides type-safe key-value pairs for use with context.Context.
Example usage:
// Create a context key. var TimeoutKey = ctxkey.New("mapreduce.Timeout", 5*time.Second) // Store a context value. ctx = mapreduce.TimeoutKey.WithValue(ctx, 10*time.Second) // Load a context value. timeout := mapreduce.TimeoutKey.Value(ctx) ... // use timeout of type time.Duration
This is inspired by https://go.dev/issue/49189.
Index ¶
- type Key
- func (key Key[Value]) Has(ctx context.Context) (ok bool)
- func (key Key[Value]) String() string
- func (key Key[Value]) Value(ctx context.Context) (v Value)
- func (key Key[Value]) ValueOk(ctx context.Context) (v Value, ok bool)
- func (key Key[Value]) WithValue(parent context.Context, val Value) context.Context
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Key ¶
type Key[Value any] struct { // contains filtered or unexported fields }
Key is a generic key type associated with a specific value type.
A zero Key is valid where the Value type itself is used as the context key. This pattern should only be used with locally declared Go types, otherwise different packages risk producing key conflicts.
Example usage:
type peerInfo struct { ... } // peerInfo is a locally declared type var peerInfoKey ctxkey.Key[peerInfo] ctx = peerInfoKey.WithValue(ctx, info) // store a context value info = peerInfoKey.Value(ctx) // load a context value
func New ¶
New constructs a new context key with an associated value type where the default value for an unpopulated value is the provided value.
The provided name is an arbitrary name only used for human debugging. As a convention, it is recommended that the name be the dot-delimited combination of the package name of the caller with the variable name. If the name is not provided, then the name of the Value type is used. Every key is unique, even if provided the same name.
Example usage:
package mapreduce var NumWorkersKey = ctxkey.New("mapreduce.NumWorkers", runtime.NumCPU())
func (Key[Value]) Value ¶
Value returns the value in the context associated with this key. If the value is not present, it returns the default value.