context

package
v1.3.0 Latest Latest
Warning

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

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

README

Context Package

Overview

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

Quick Start

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

Configuration

The context package does not require any specific configuration. It can be used directly without any setup.

API Documentation

Core Types
Context Keys

The package provides strongly typed keys for context values to ensure type safety.

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

Key Methods
Value Management

The package provides methods for setting and getting values from a context.

See the Value Propagation Example for a complete, runnable example of how to use value management methods.

Timeout Management

The package provides methods for working with context deadlines and timeouts.

See the Timeout Example for a complete, runnable example of how to use timeout management methods.

Error Handling

The package provides methods for handling errors in context operations.

See the Error Handling Example for a complete, runnable example of how to handle errors.

Examples

For complete, runnable examples, see the following files in the examples directory:

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.

Troubleshooting

Common Issues
Context Cancellation Not Propagating

Issue: Context cancellation is not being propagated to child goroutines.

Solution: Ensure that you're passing the context to all functions and goroutines that should respect cancellation. Check that you're properly selecting on ctx.Done() in long-running operations.

Context Values Not Found

Issue: Context values are not being found when expected.

Solution: Ensure that you're using the correct key type and that the value was actually set in the context. Remember that context values are immutable, so you need to capture the return value of context.WithValue().

Deadlines Not Being Respected

Issue: Operations are not respecting context deadlines.

Solution: Ensure that you're checking ctx.Err() regularly in long-running operations. Use select statements with ctx.Done() to abort operations when the context is cancelled or times out.

  • Logging - The logging component uses context for request-scoped logging.
  • Telemetry - The telemetry component uses context for propagating trace information.
  • Middleware - The middleware component uses context for request processing.
  • Auth - The auth component uses context for storing authentication information.

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.

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