contextx

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 3 Imported by: 0

README

contextx

上下文类型安全辅助工具。提供类型安全的 context key、deadline 查询和取消原因获取。

Typed context helpers. Provides type-safe context keys, deadline queries, and cancel cause extraction.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CancelCause

func CancelCause(ctx context.Context) error

CancelCause returns the cancellation cause, or nil if not cancelled.

func DeadlineRemaining

func DeadlineRemaining(ctx context.Context, clock timex.Clock) (time.Duration, bool)

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

func HasDeadline(ctx context.Context) bool

HasDeadline reports whether the context has a deadline set.

func IsDone

func IsDone(ctx context.Context) bool

IsDone reports whether the context is done (cancelled or deadline exceeded).

func Value

func Value[T any](ctx context.Context, key Key[T]) (T, bool)

Value extracts a typed value from the context. Returns (value, true) if present, (zero, false) otherwise.

func WithValue

func WithValue[T any](ctx context.Context, key Key[T], value T) context.Context

WithValue returns a derived context with the typed key-value pair.

Types

type Key

type Key[T any] struct {
	// contains filtered or unexported fields
}

Key is a typed context key that prevents value collisions.

func NewKey

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

NewKey creates a new typed context key with the given name. Each call returns a distinct key, even with the same name and type.

Jump to

Keyboard shortcuts

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