Documentation
¶
Overview ¶
Package contextx provides type-safe context helpers.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/ZoneCNH/kernel/contextx"
"github.com/ZoneCNH/kernel/timex"
)
func main() {
// Create typed keys
requestID := contextx.NewKey[string]("request-id")
userID := contextx.NewKey[int]("user-id")
// Set values in context
ctx := context.Background()
ctx = contextx.WithValue(ctx, requestID, "abc-123")
ctx = contextx.WithValue(ctx, userID, 42)
// Get values
if id, ok := contextx.Value(ctx, requestID); ok {
fmt.Println("Request ID:", id)
}
if id, ok := contextx.Value(ctx, userID); ok {
fmt.Println("User ID:", id)
}
// Check deadline
fmt.Println("Has deadline:", contextx.HasDeadline(ctx))
// Use with clock for testing
clock := timex.NewFixedClock(time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC))
_, hasDeadline := contextx.DeadlineRemaining(ctx, clock)
fmt.Println("Deadline remaining:", hasDeadline)
}
Output: Request ID: abc-123 User ID: 42 Has deadline: false Deadline remaining: false
Index ¶
- func CancelCause(ctx context.Context) error
- func DeadlineRemaining(ctx context.Context, clock timex.Clock) (time.Duration, bool)
- func HasDeadline(ctx context.Context) bool
- func IsDone(ctx context.Context) bool
- func Value[T any](ctx context.Context, key Key[T]) (T, bool)
- func WithValue[T any](ctx context.Context, key Key[T], value T) context.Context
- type Key
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CancelCause ¶
CancelCause returns the cancellation cause, or nil if not cancelled.
func DeadlineRemaining ¶
DeadlineRemaining returns the remaining time until the context deadline. Uses the provided clock for deterministic testing. Returns (duration, true) if deadline exists, (0, false) otherwise.
func HasDeadline ¶
HasDeadline reports whether the context has a deadline set.
Types ¶
Click to show internal directories.
Click to hide internal directories.