context

package
v1.6.0 Latest Latest
Warning

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

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

README

Context

Overview

The Context component provides utilities for working with Go's standard context package. It extends the functionality with additional features for managing request-specific data, timeouts, and error handling in distributed systems.

Features

  • Enhanced Context Creation: Create contexts with various timeouts and built-in metadata
  • Automatic ID Generation: Generate and manage request IDs, trace IDs, and correlation IDs
  • Timeout Management: Predefined timeouts for common operations (database, network, external services)
  • Context Value Management: Add and retrieve values from contexts with type safety
  • Error Handling: Utilities for checking context status and handling context errors
  • Context Information: Generate comprehensive context information for logging and debugging

Installation

go get github.com/abitofhelp/servicelib/context

Quick Start

See the Basic Usage example for a complete, runnable example of how to use the context component.

API Documentation

Core Types
Key

A type for context keys to avoid collisions.

type Key string
ContextOptions

Options for creating a new context.

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
}
Key Methods
NewContext

Creates a new context with the specified options.

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

Creates a new context with the specified timeout and options.

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

Checks if the context is done and returns an appropriate error.

func CheckContext(ctx context.Context) error
WithValues

Creates a new context with the specified key-value pairs.

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

Returns a string with all the context information.

func ContextInfo(ctx context.Context) string

Examples

For complete, runnable examples, see the following directories in the EXAMPLES directory:

Best Practices

  1. Always Pass Context First: Make context the first parameter in functions that need it
  2. Use Appropriate Timeouts: Choose the right timeout function for your operation type
  3. Check Context Status: Regularly check if the context is done to allow for early cancellation
  4. Propagate Context Values: Pass relevant context values down the call stack
  5. Don't Store Contexts: Contexts should be passed as parameters, not stored in structs

Troubleshooting

Common Issues
Context Deadline Exceeded

If you're seeing "context deadline exceeded" errors, your operation is taking longer than the timeout allows. Consider:

  • Increasing the timeout duration
  • Optimizing the operation to complete faster
  • Breaking the operation into smaller parts
Context Canceled

If you're seeing "context canceled" errors, the context was explicitly canceled. This is often intentional, but if not, check:

  • If a parent context is being canceled unexpectedly
  • If cancel() is being called too early
  • If the wrong context is being passed to functions
  • Errors - Error handling for context-related errors
  • Logging - Logging with context information
  • Telemetry - Distributed tracing with context propagation

Contributing

Contributions to this component are welcome! Please see the Contributing Guide for more information.

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.

Package context provides utilities for working with Go's standard context package.

This package extends the functionality of the standard context package by providing:

  • Context creation with various timeout configurations (default, short, long, etc.)
  • Context enrichment with common metadata (request ID, trace ID, user ID, etc.)
  • Helper functions for retrieving context values
  • Context validation and error handling

The package is designed to standardize context usage across the application and ensure that all contexts contain the necessary metadata for tracing, logging, and error handling.

Key features:

  • Predefined timeout constants for different types of operations
  • Automatic generation of unique IDs (request ID, trace ID, correlation ID)
  • Context validation to handle timeouts and cancellations gracefully
  • Structured context information for logging and debugging

Example usage:

// Create a new context with default timeout and operation name
ctx, cancel := context.NewContext(context.ContextOptions{
    Timeout:   context.DefaultTimeout,
    Operation: "fetch_user_data",
})
defer cancel()

// Add user ID to the context
ctx = context.WithUserID(ctx, "user123")

// Check if the context is still valid before proceeding
if err := context.CheckContext(ctx); err != nil {
    return err
}

// Get context information for logging
logger.Info("Processing request", zap.String("context", context.ContextInfo(ctx)))

Index

Constants

View Source
const (
	// DefaultTimeout is the standard timeout for general operations (30 seconds).
	DefaultTimeout = 30 * time.Second

	// ShortTimeout is a brief timeout for quick operations (5 seconds).
	ShortTimeout = 5 * time.Second

	// LongTimeout is an extended timeout for operations that may take longer (60 seconds).
	LongTimeout = 60 * time.Second

	// DatabaseTimeout is the timeout for database operations (10 seconds).
	DatabaseTimeout = 10 * time.Second

	// NetworkTimeout is the timeout for network operations (15 seconds).
	NetworkTimeout = 15 * time.Second

	// ExternalServiceTimeout is the timeout for calls to external services (20 seconds).
	ExternalServiceTimeout = 20 * time.Second
)

Default timeout values define standard durations for different types of operations. These constants should be used consistently throughout the application to ensure that timeouts are appropriate for the type of operation being performed.

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. This is a wrapper around context.Background() from the standard library.

Returns:

  • context.Context: A background context that is never canceled.

func CheckContext

func CheckContext(ctx context.Context) error

CheckContext checks if the context is done and returns an appropriate error. This function is useful for checking if a context has been canceled or has timed out before proceeding with an operation. It returns nil if the context is still valid, or an appropriate error if the context is done.

Parameters:

  • ctx: The context to check.

Returns:

  • error: nil if the context is still valid, or an error describing why the context is done. The error will be errors.ErrTimeout if the context timed out, errors.ErrCanceled if the context was canceled, or a wrapped error for other context errors.

func ContextInfo

func ContextInfo(ctx context.Context) string

ContextInfo returns a string with all the context information. This function creates a formatted string containing all the metadata stored in the context, including request ID, trace ID, user ID, tenant ID, operation name, correlation ID, service name, and deadline (if set). This is useful for logging and debugging.

Parameters:

  • ctx: The context from which to retrieve the information.

Returns:

  • string: A formatted string containing all the context information.

func GetCorrelationID

func GetCorrelationID(ctx context.Context) string

GetCorrelationID gets the correlation ID from the context. This function retrieves the correlation ID that was previously set with WithCorrelationID.

Parameters:

  • ctx: The context from which to retrieve the correlation ID.

Returns:

  • string: The correlation ID, or an empty string if no correlation ID was set.

func GetOperation

func GetOperation(ctx context.Context) string

GetOperation gets the operation name from the context. This function retrieves the operation name that was previously set with WithOperation.

Parameters:

  • ctx: The context from which to retrieve the operation name.

Returns:

  • string: The operation name, or an empty string if no operation name was set.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID gets the request ID from the context. This function retrieves the request ID that was previously set with WithRequestID.

Parameters:

  • ctx: The context from which to retrieve the request ID.

Returns:

  • string: The request ID, or an empty string if no request ID was set.

func GetServiceName

func GetServiceName(ctx context.Context) string

GetServiceName gets the service name from the context. This function retrieves the service name that was previously set with WithServiceName.

Parameters:

  • ctx: The context from which to retrieve the service name.

Returns:

  • string: The service name, or an empty string if no service name was set.

func GetTenantID

func GetTenantID(ctx context.Context) string

GetTenantID gets the tenant ID from the context. This function retrieves the tenant ID that was previously set with WithTenantID.

Parameters:

  • ctx: The context from which to retrieve the tenant ID.

Returns:

  • string: The tenant ID, or an empty string if no tenant ID was set.

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID gets the trace ID from the context. This function retrieves the trace ID that was previously set with WithTraceID.

Parameters:

  • ctx: The context from which to retrieve the trace ID.

Returns:

  • string: The trace ID, or an empty string if no trace ID was set.

func GetUserID

func GetUserID(ctx context.Context) string

GetUserID gets the user ID from the context. This function retrieves the user ID that was previously set with WithUserID.

Parameters:

  • ctx: The context from which to retrieve the user ID.

Returns:

  • string: The user ID, or an empty string if no user ID was set.

func MustCheck

func MustCheck(ctx context.Context)

MustCheck checks if the context is done and panics with an appropriate error if it is. This function is similar to CheckContext, but instead of returning an error, it panics if the context is done. This is useful in situations where a context error should be treated as a fatal error.

Parameters:

  • ctx: The context to check.

Panics:

  • If the context is done, this function will panic with the error returned by CheckContext.

func NewContext

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

NewContext creates a new context with the specified options. It enriches the context with metadata from the provided options and applies a timeout if specified.

Parameters:

  • opts: The options for creating the context, including timeout, metadata, and parent context.

Returns:

  • context.Context: The newly created context with all specified options applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func TODO

func TODO() context.Context

TODO returns a non-nil, empty Context. This is a wrapper around context.TODO() from the standard library. Code should use 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).

Returns:

  • context.Context: A TODO context that indicates the context should be provided in the future.

func WithCorrelationID

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

WithCorrelationID adds a correlation ID to the context. The correlation ID is used to track related operations across multiple services or components, especially in distributed systems.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • correlationID: The correlation ID to add to the context.

Returns:

  • context.Context: The newly created context with the correlation ID added.

func WithDatabaseTimeout

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

WithDatabaseTimeout creates a new context with a database timeout (10 seconds). This is a convenience function for creating a context specifically for database operations. It also sets the operation name to "database" for better error reporting and logging.

Parameters:

  • ctx: The parent context from which the new context will be derived.

Returns:

  • context.Context: The newly created context with the database timeout applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func WithDefaultTimeout

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

WithDefaultTimeout creates a new context with the default timeout (30 seconds). This is a convenience function for creating a context with a standard timeout for general operations.

Parameters:

  • ctx: The parent context from which the new context will be derived.

Returns:

  • context.Context: The newly created context with the default timeout applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func WithExternalServiceTimeout

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

WithExternalServiceTimeout creates a new context with an external service timeout (20 seconds). This is a convenience function for creating a context specifically for external service calls. It sets the operation name to "external_service" and includes the service name for better error reporting and logging.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • serviceName: The name of the external service being called.

Returns:

  • context.Context: The newly created context with the external service timeout applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func WithLongTimeout

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

WithLongTimeout creates a new context with a long timeout (60 seconds). This is a convenience function for creating a context with an extended timeout for operations that may take longer to complete.

Parameters:

  • ctx: The parent context from which the new context will be derived.

Returns:

  • context.Context: The newly created context with the long timeout applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func WithNetworkTimeout

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

WithNetworkTimeout creates a new context with a network timeout (15 seconds). This is a convenience function for creating a context specifically for network operations. It also sets the operation name to "network" for better error reporting and logging.

Parameters:

  • ctx: The parent context from which the new context will be derived.

Returns:

  • context.Context: The newly created context with the network timeout applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func WithOperation

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

WithOperation creates a new context with an operation name. The operation name is used for logging, error reporting, and tracing to identify the specific operation being performed.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • operation: The name of the operation being performed.

Returns:

  • context.Context: The newly created context with the operation name added.

func WithRequestID

func WithRequestID(ctx context.Context) context.Context

WithRequestID adds a request ID to the context. This function generates a new UUID and adds it to the context as the request ID. The request ID is useful for tracking requests through the system, especially in logs and error reports.

Parameters:

  • ctx: The parent context from which the new context will be derived.

Returns:

  • context.Context: The newly created context with a request ID added.

func WithServiceName

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

WithServiceName adds a service name to the context. The service name is used to identify the service handling the request, which is useful for logging, error reporting, and distributed tracing.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • serviceName: The name of the service to add to the context.

Returns:

  • context.Context: The newly created context with the service name added.

func WithShortTimeout

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

WithShortTimeout creates a new context with a short timeout (5 seconds). This is a convenience function for creating a context with a brief timeout for operations that should complete quickly.

Parameters:

  • ctx: The parent context from which the new context will be derived.

Returns:

  • context.Context: The newly created context with the short timeout applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func WithTenantID

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

WithTenantID adds a tenant ID to the context. The tenant ID is useful for multi-tenant applications, allowing operations to be associated with a specific tenant for data isolation and authorization.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • tenantID: The ID of the tenant to add to the context.

Returns:

  • context.Context: The newly created context with the tenant ID added.

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. It applies the timeout to the context and enriches it with metadata from the provided options.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • timeout: The duration after which the context will be canceled.
  • opts: The options for creating the context, including metadata.

Returns:

  • context.Context: The newly created context with timeout and options applied.
  • context.CancelFunc: A cancel function that can be called to cancel the context.

func WithTraceID

func WithTraceID(ctx context.Context) context.Context

WithTraceID adds a trace ID to the context. This function generates a new UUID and adds it to the context as the trace ID. The trace ID is useful for distributed tracing, allowing requests to be tracked across multiple services.

Parameters:

  • ctx: The parent context from which the new context will be derived.

Returns:

  • context.Context: The newly created context with a trace ID added.

func WithUserID

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

WithUserID adds a user ID to the context. The user ID is useful for authentication, authorization, and auditing purposes. It allows operations to be associated with a specific user.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • userID: The ID of the user to add to the context.

Returns:

  • context.Context: The newly created context with the user ID added.

func WithValues

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

WithValues creates a new context with the specified key-value pairs. This function allows adding multiple key-value pairs to a context in a single call. The keys and values are provided as alternating arguments, where each key is followed by its corresponding value.

Parameters:

  • ctx: The parent context from which the new context will be derived.
  • keyValues: Alternating key-value pairs to add to the context. The number of arguments should be even. If an odd number of arguments is provided, the last one is ignored.

Returns:

  • context.Context: The newly created context with all key-value pairs added.

Types

type ContextOptions

type ContextOptions struct {
	// Timeout is the duration after which the context will be canceled.
	// If set to 0, no timeout will be applied.
	Timeout time.Duration

	// RequestID is a unique identifier for the request.
	// If empty, a new UUID will be generated.
	RequestID string

	// TraceID is a unique identifier for distributed tracing.
	// If empty, a new UUID will be generated.
	TraceID string

	// UserID is the ID of the user making the request.
	// This is useful for authentication and authorization.
	UserID string

	// TenantID is the ID of the tenant in multi-tenant applications.
	// This is useful for data isolation and authorization.
	TenantID string

	// Operation is the name of the operation being performed.
	// This is useful for logging and error reporting.
	Operation string

	// CorrelationID is a unique identifier for correlating related operations.
	// If empty, a new UUID will be generated.
	CorrelationID string

	// ServiceName is the name of the service handling the request.
	// This is useful for distributed tracing and logging.
	ServiceName string

	// Parent is the parent context from which the new context will be derived.
	// If nil, context.Background() will be used.
	Parent context.Context
}

ContextOptions contains options for creating a new context. This struct allows for flexible context creation with various metadata and configuration options.

type Key

type Key string

Key represents a key for context values in the context package. It is a type alias for string that provides type safety for context keys.

const (
	// RequestIDKey is the key for storing and retrieving the request ID.
	RequestIDKey Key = "request_id"

	// TraceIDKey is the key for storing and retrieving the trace ID.
	TraceIDKey Key = "trace_id"

	// UserIDKey is the key for storing and retrieving the user ID.
	UserIDKey Key = "user_id"

	// TenantIDKey is the key for storing and retrieving the tenant ID.
	TenantIDKey Key = "tenant_id"

	// OperationKey is the key for storing and retrieving the operation name.
	OperationKey Key = "operation"

	// CorrelationIDKey is the key for storing and retrieving the correlation ID.
	CorrelationIDKey Key = "correlation_id"

	// ServiceNameKey is the key for storing and retrieving the service name.
	ServiceNameKey Key = "service_name"
)

Context keys define the standard keys used for storing and retrieving values from contexts. These keys should be used consistently throughout the application to ensure that context values can be reliably accessed.

Jump to

Keyboard shortcuts

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