contextkey

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 1 Imported by: 0

README

ContextKey

Type-safe context key management for Go using generics.

ContextKey provides type-safe context key implementations with compile-time type safety, eliminating the need for type assertions and reducing runtime errors when working with Go's context values.

Installation

go get github.com/eriicafes/httpx

Usage

Define a context key

Create a context key with a specific type using New. The type parameter determines what values can be stored.

package main

import (
    "context"
    "github.com/eriicafes/httpx/contextkey"
)

var (
    userIDKey    = contextkey.New[int]("userID")
    requestIDKey = contextkey.New[string]("requestID")
    userKey      = contextkey.New[*User]("user")
)

type User struct {
    ID   int
    Name string
}
Set and get values
func main() {
    ctx := context.Background()

    // Set a value
    ctx = userIDKey.Set(ctx, 12345)

    // Get a value
    if id, ok := userIDKey.Get(ctx); ok {
        fmt.Println("User ID:", id) // User ID: 12345
    }
}
Delete values
ctx = userIDKey.Set(ctx, 12345)

// Remove the value
ctx = userIDKey.Delete(ctx)

if _, ok := userIDKey.Get(ctx); !ok {
    fmt.Println("User ID not found")
}
Take values (get and delete)

Take retrieves a value and removes it from the context in a single operation.

ctx = requestIDKey.Set(ctx, "abc-123")

// Get and remove in one operation
newCtx, requestID, ok := requestIDKey.Take(ctx)
if ok {
    fmt.Println("Request ID:", requestID) // Request ID: abc-123
}

// Value is now removed from newCtx
if _, ok := requestIDKey.Get(newCtx); !ok {
    fmt.Println("Request ID no longer in context")
}
Update values

Update modifies an existing value or sets a new one using an update function.

ctx = userIDKey.Set(ctx, 100)

// Increment the user ID
ctx = userIDKey.Update(ctx, func(prev int, hasPrev bool) int {
    if hasPrev {
        return prev + 1
    }
    return 1 // Default value if not set
})

if id, ok := userIDKey.Get(ctx); ok {
    fmt.Println("Updated ID:", id) // Updated ID: 101
}

Benefits

  • Type safety: Compile-time type checking prevents type mismatches
  • No type assertions: Values are returned with the correct type automatically
  • Clear API: Explicit methods for common operations (Get, Set, Delete, Take, Update)
  • Zero dependencies: Uses only the standard library
  • Lightweight: Minimal overhead over native context operations

Documentation

Overview

Package contextkey provides type-safe context key management using Go generics. It wraps the standard context.Context value storage with compile-time type safety, eliminating the need for type assertions and reducing runtime errors.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Key

type Key[T any] interface {
	// Get retrieves the value associated with this key from the context.
	// Returns the value and true if found, or the zero value and false if not found.
	Get(context.Context) (T, bool)

	// Set stores a value in the context and returns a new context with the value set.
	Set(context.Context, T) context.Context

	// Delete removes the value associated with this key from the context.
	// Returns a new context with the value removed.
	Delete(context.Context) context.Context

	// Take retrieves and removes the value in a single operation.
	// Returns the new context, the value, and whether the value was found.
	// If the value doesn't exist, returns the original context and the zero value.
	Take(context.Context) (context.Context, T, bool)

	// Update modifies the existing value using the provided update function.
	// The update function receives the previous value and whether it existed.
	// Returns a new context with the updated value.
	Update(ctx context.Context, update func(prev T, hasPrev bool) T) context.Context
}

Key is a type-safe interface for storing and retrieving values in a context. It provides compile-time type safety for context values through Go generics.

func New

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

New creates a new type-safe context key with the given name. The name should be unique to avoid collisions with other context keys.

Jump to

Keyboard shortcuts

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