package ctxkey
import "tailscale.com/util/ctxkey"
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 New[Value any](name string, defaultValue Value) Key[Value]
- 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
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]) Has ¶
Has reports whether the context has a value for this key.
func (Key[Value]) String ¶
String returns the name of the key.
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.
func (Key[Value]) ValueOk ¶
ValueOk returns the value in the context associated with this key and also reports whether it was present. If the value is not present, it returns the default value.
func (Key[Value]) WithValue ¶
WithValue returns a copy of parent in which the value associated with key is val.
It is a type-safe equivalent of context.WithValue.
Source Files ¶
key.go
- Version
- v1.84.0 (latest)
- Published
- May 21, 2025
- Platform
- linux/amd64
- Imports
- 3 packages
- Last checked
- 46 seconds ago –
Tools for package owners.