context

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2025 License: MIT Imports: 5 Imported by: 0

README

Context Package

The context package extends Go's standard context package with additional utilities for request handling, cancellation, and value propagation. It provides a set of helper functions and types to make working with contexts easier and more type-safe.

Features

  • Value Management: Strongly typed context values
  • Timeout Management: Utilities for working with context deadlines
  • Cancellation: Simplified cancellation patterns
  • Propagation: Utilities for propagating context values across service boundaries

Installation

go get github.com/abitofhelp/servicelib/context

Usage

Value Management
package main

import (
    "fmt"
    "context"
    "github.com/abitofhelp/servicelib/context"
)

// Define a type-safe key
type userIDKey struct{}

func main() {
    // Create a context with a value
    ctx := context.WithValue(context.Background(), userIDKey{}, "user-123")
    
    // Get a value from the context
    userID, ok := context.GetValue[string](ctx, userIDKey{})
    if ok {
        fmt.Println("User ID:", userID)
    }
    
    // Using helper functions
    ctx = context.WithUserID(ctx, "user-456")
    userID = context.GetUserID(ctx)
    fmt.Println("User ID:", userID)
}
Timeout Management
package main

import (
    "fmt"
    "time"
    "context"
    "github.com/abitofhelp/servicelib/context"
)

func main() {
    // Create a context with a timeout
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    // Check if the context has a deadline
    if deadline, ok := context.GetDeadline(ctx); ok {
        fmt.Printf("Context will expire at: %v\n", deadline)
        fmt.Printf("Time remaining: %v\n", context.GetRemainingTime(ctx))
    }
    
    // Execute a function with a timeout
    result, err := context.ExecuteWithTimeout(ctx, func(ctx context.Context) (string, error) {
        // Simulate work
        time.Sleep(2 * time.Second)
        return "Success", nil
    })
    
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result)
    }
}
Cancellation
package main

import (
    "fmt"
    "time"
    "context"
    "github.com/abitofhelp/servicelib/context"
)

func main() {
    // Create a cancellable context
    ctx, cancel := context.WithCancel(context.Background())
    
    // Start a goroutine that will be cancelled
    go func() {
        select {
        case <-ctx.Done():
            fmt.Println("Goroutine cancelled")
            return
        case <-time.After(10 * time.Second):
            fmt.Println("Goroutine completed")
        }
    }()
    
    // Cancel the context after 2 seconds
    time.Sleep(2 * time.Second)
    cancel()
    
    // Wait to see the output
    time.Sleep(1 * time.Second)
}
Propagation
package main

import (
    "fmt"
    "context"
    "net/http"
    "github.com/abitofhelp/servicelib/context"
)

func main() {
    // Create an HTTP handler that propagates context values
    http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
        // Extract values from the request context
        ctx := r.Context()
        
        // Add a request ID to the context
        ctx = context.WithRequestID(ctx, "req-123")
        
        // Call a service function with the context
        result := serviceFunction(ctx)
        
        fmt.Fprintf(w, "Result: %s", result)
    })
    
    http.ListenAndServe(":8080", nil)
}

func serviceFunction(ctx context.Context) string {
    // Get values from the context
    requestID := context.GetRequestID(ctx)
    
    // Use the values
    return fmt.Sprintf("Processing request %s", requestID)
}

Common Context Values

The package provides helpers for common context values:

// Request ID
ctx = context.WithRequestID(ctx, "req-123")
requestID := context.GetRequestID(ctx)

// User ID
ctx = context.WithUserID(ctx, "user-456")
userID := context.GetUserID(ctx)

// Tenant ID
ctx = context.WithTenantID(ctx, "tenant-789")
tenantID := context.GetTenantID(ctx)

// Correlation ID
ctx = context.WithCorrelationID(ctx, "corr-abc")
correlationID := context.GetCorrelationID(ctx)

// Transaction ID
ctx = context.WithTransactionID(ctx, "tx-def")
transactionID := context.GetTransactionID(ctx)

Best Practices

  1. Type Safety: Use strongly typed keys for context values to avoid runtime type errors.

  2. Context Propagation: Always propagate context through your application, especially across API boundaries.

  3. Cancellation: Use context cancellation to properly clean up resources and prevent goroutine leaks.

  4. Timeout Management: Set appropriate timeouts for operations to prevent hanging requests.

  5. Value Scope: Context values should be request-scoped and not used for passing optional parameters to functions.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package context provides utilities for working with Go's context package. It includes functions for creating contexts with various timeouts, adding and retrieving values from contexts, and checking context status.

Index

Constants

View Source
const (
	DefaultTimeout         = 30 * time.Second
	ShortTimeout           = 5 * time.Second
	LongTimeout            = 60 * time.Second
	DatabaseTimeout        = 10 * time.Second
	NetworkTimeout         = 15 * time.Second
	ExternalServiceTimeout = 20 * time.Second
)

Default timeout values

Variables

This section is empty.

Functions

func Background

func Background() context.Context

Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline.

func CheckContext

func CheckContext(ctx context.Context) error

CheckContext checks if the context is done and returns an appropriate error

func ContextInfo

func ContextInfo(ctx context.Context) string

ContextInfo returns a string with all the context information

func GetCorrelationID

func GetCorrelationID(ctx context.Context) string

GetCorrelationID gets the correlation ID from the context

func GetOperation

func GetOperation(ctx context.Context) string

GetOperation gets the operation name from the context

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID gets the request ID from the context

func GetServiceName

func GetServiceName(ctx context.Context) string

GetServiceName gets the service name from the context

func GetTenantID

func GetTenantID(ctx context.Context) string

GetTenantID gets the tenant ID from the context

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID gets the trace ID from the context

func GetUserID

func GetUserID(ctx context.Context) string

GetUserID gets the user ID from the context

func MustCheck

func MustCheck(ctx context.Context)

MustCheck checks if the context is done and panics with an appropriate error if it is

func NewContext

func NewContext(opts ContextOptions) (context.Context, context.CancelFunc)

NewContext creates a new context with the specified options

func TODO

func TODO() context.Context

TODO returns a non-nil, empty Context. Code should use context.TODO when it's unclear which Context to use or it is not yet available (because the surrounding function has not yet been extended to accept a Context parameter).

func WithCorrelationID

func WithCorrelationID(ctx context.Context, correlationID string) context.Context

WithCorrelationID adds a correlation ID to the context

func WithDatabaseTimeout

func WithDatabaseTimeout(ctx context.Context) (context.Context, context.CancelFunc)

WithDatabaseTimeout creates a new context with a database timeout

func WithDefaultTimeout

func WithDefaultTimeout(ctx context.Context) (context.Context, context.CancelFunc)

WithDefaultTimeout creates a new context with the default timeout

func WithExternalServiceTimeout

func WithExternalServiceTimeout(ctx context.Context, serviceName string) (context.Context, context.CancelFunc)

WithExternalServiceTimeout creates a new context with an external service timeout

func WithLongTimeout

func WithLongTimeout(ctx context.Context) (context.Context, context.CancelFunc)

WithLongTimeout creates a new context with a long timeout

func WithNetworkTimeout

func WithNetworkTimeout(ctx context.Context) (context.Context, context.CancelFunc)

WithNetworkTimeout creates a new context with a network timeout

func WithOperation

func WithOperation(ctx context.Context, operation string) context.Context

WithOperation creates a new context with an operation name

func WithRequestID

func WithRequestID(ctx context.Context) context.Context

WithRequestID adds a request ID to the context

func WithServiceName

func WithServiceName(ctx context.Context, serviceName string) context.Context

WithServiceName adds a service name to the context

func WithShortTimeout

func WithShortTimeout(ctx context.Context) (context.Context, context.CancelFunc)

WithShortTimeout creates a new context with a short timeout

func WithTenantID

func WithTenantID(ctx context.Context, tenantID string) context.Context

WithTenantID adds a tenant ID to the context

func WithTimeout

func WithTimeout(ctx context.Context, timeout time.Duration, opts ContextOptions) (context.Context, context.CancelFunc)

WithTimeout creates a new context with the specified timeout and options

func WithTraceID

func WithTraceID(ctx context.Context) context.Context

WithTraceID adds a trace ID to the context

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds a user ID to the context

func WithValues

func WithValues(ctx context.Context, keyValues ...interface{}) context.Context

WithValues creates a new context with the specified key-value pairs

Types

type ContextOptions

type ContextOptions struct {
	// Timeout is the duration after which the context will be canceled
	Timeout time.Duration

	// RequestID is a unique identifier for the request
	RequestID string

	// TraceID is a unique identifier for tracing
	TraceID string

	// UserID is the ID of the user making the request
	UserID string

	// TenantID is the ID of the tenant
	TenantID string

	// Operation is the name of the operation being performed
	Operation string

	// CorrelationID is a unique identifier for correlating related operations
	CorrelationID string

	// ServiceName is the name of the service
	ServiceName string

	// Parent is the parent context
	Parent context.Context
}

ContextOptions contains options for creating a context

type Key

type Key string

Key represents a key for context values

const (
	RequestIDKey     Key = "request_id"
	TraceIDKey       Key = "trace_id"
	UserIDKey        Key = "user_id"
	TenantIDKey      Key = "tenant_id"
	OperationKey     Key = "operation"
	CorrelationIDKey Key = "correlation_id"
	ServiceNameKey   Key = "service_name"
)

Context keys

Jump to

Keyboard shortcuts

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