ctx := context.WithValue(parentCtx, "key", "value") if value, ok := ctx.Value("key").(string); ok { // do something with value }
type requestIDKey struct{} func RequestID(ctx context.Context) (string, bool) { id, ok := ctx.Value(requestIDKey{}).(string) return id, ok } func WithRequestID(ctx context.Context, id string) context.Context { return context.WithValue(ctx, requestIDKey{}, id) }In this example, we define a custom key type and use it to store a request ID in a context. We also define helper functions for getting and setting the request ID in the context. The context.Context Value is part of the standard library of the Go programming language, located in the `context` package (`"golang.org/x/net/context"` is an older package that has been replaced by `"context"`).