servicelib

module
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

README

ServiceLib

Overview

ServiceLib is a comprehensive Go library designed to provide a robust foundation for building scalable, maintainable, and production-ready microservices. It offers a collection of packages that address common challenges in service development, from authentication and configuration to error handling and telemetry.

Features

  • Authentication & Authorization: Secure your services with JWT, OIDC, and role-based access control
  • Configuration Management: Flexible configuration with support for multiple sources and formats
  • Error Handling: Structured error types with context, stack traces, and categorization
  • Database Access: Connection management, health checks, and transaction support
  • Dependency Injection: Simple yet powerful DI container for managing service dependencies
  • Telemetry: Integrated logging, metrics, and distributed tracing
  • Health Checks: Standardized health check endpoints and status reporting
  • Middleware: Common HTTP middleware for logging, error handling, and more
  • Retry & Circuit Breaking: Resilience patterns for handling transient failures
  • Validation: Comprehensive input validation utilities

Installation

go get github.com/abitofhelp/servicelib

Quick Start

Basic HTTP Server

Here's a simple example of creating an HTTP server with ServiceLib:

package main

import (
	"context"
	"log"
	"net/http"

	"github.com/abitofhelp/servicelib/logging"
	"github.com/abitofhelp/servicelib/middleware"
	"go.uber.org/zap"
)

func main() {
	// Create a logger
	logger, err := logging.NewLogger("info", true)
	if err != nil {
		log.Fatalf("Failed to initialize logger: %v", err)
	}
	defer logger.Sync()

	// Create a context logger
	contextLogger := logging.NewContextLogger(logger)

	// Create a simple HTTP handler
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello, ServiceLib!"))
	})

	// Add middleware for logging, metrics, and recovery
	handler := middleware.Chain(
		mux,
		middleware.WithRequestID(context.Background()),
		middleware.Logging(contextLogger),
		middleware.Recovery(contextLogger),
	)

	// Start the server
	contextLogger.Info(context.Background(), "Starting server", zap.String("address", ":8080"))
	if err := http.ListenAndServe(":8080", handler); err != nil {
		contextLogger.Fatal(context.Background(), "Server failed", zap.Error(err))
	}
}
Error Handling

ServiceLib provides a comprehensive error handling system:

package main

import (
	"context"
	"database/sql"
	"fmt"
	"net/http"

	"github.com/abitofhelp/servicelib/errors"
	errhttp "github.com/abitofhelp/servicelib/errors/http"
	errlog "github.com/abitofhelp/servicelib/errors/log"
	"github.com/abitofhelp/servicelib/logging"
	"go.uber.org/zap"
)

// GetUserByID retrieves a user by ID with proper error handling
func GetUserByID(ctx context.Context, logger *logging.ContextLogger, id string) (*User, error) {
	// Validate input
	if id == "" {
		// Create a validation error
		err := errors.NewValidationError("User ID is required", "id", nil)

		// Log the error
		errlog.LogError(ctx, logger, err)

		return nil, err
	}

	// Simulate a database error
	if id == "db-error" {
		dbErr := sql.ErrNoRows
		err := errors.NewDatabaseError("Failed to query user", "SELECT", "users", dbErr)

		// Log the error
		errlog.LogError(ctx, logger, err)

		return nil, err
	}

	// Return a user
	return &User{ID: id, Name: "John Doe"}, nil
}

// HTTP handler with error handling
func GetUserHandler(w http.ResponseWriter, r *http.Request, service *UserService) {
	// Get user ID from request
	id := r.URL.Query().Get("id")

	// Get user from service
	user, err := service.GetUserByID(r.Context(), id)
	if err != nil {
		// Write error response with appropriate status code
		errhttp.WriteError(w, err)
		return
	}

	// Write success response
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, `{"id":"%s","name":"%s"}`, user.ID, user.Name)
}

For more examples, see the Examples directory.

Packages

ServiceLib is organized into the following packages:

  • auth - Authentication and authorization
  • cache - Caching utilities
  • circuit - Circuit breaker implementation
  • config - Configuration management
  • context - Context utilities
  • date - Date and time utilities
  • db - Database access and management
  • di - Dependency injection
  • env - Environment variable utilities
  • errors - Error handling, management, and recovery patterns
  • graphql - GraphQL utilities
  • health - Health check utilities
  • logging - Structured logging
  • middleware - HTTP middleware
  • model - Model utilities
  • rate - Rate limiting
  • repository - Repository pattern implementation
  • retry - Retry utilities
  • shutdown - Graceful shutdown utilities
  • signal - Signal handling
  • stringutil - String utilities
  • telemetry - Telemetry (metrics, tracing)
  • transaction - Transaction management
  • validation - Input validation
  • valueobject - Value object implementations

Examples

For complete, runnable examples of each component, see the EXAMPLES directory.

Architecture Diagrams

The following UML diagrams provide a visual representation of the ServiceLib architecture:

Contributing

Contributions to ServiceLib 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.

Directories

Path Synopsis
EXAMPLES
auth/auth_instance command
Example usage of creating an Auth instance
Example usage of creating an Auth instance
auth/authorization command
Example demonstrating authorization concepts
Example demonstrating authorization concepts
auth/configuration command
Example usage of the Auth module configuration
Example usage of the Auth module configuration
auth/context_utilities command
Example demonstrating context utilities for authentication
Example demonstrating context utilities for authentication
auth/error_handling command
Example demonstrating error handling in the auth module
Example demonstrating error handling in the auth module
auth/middleware command
Example usage of the Auth middleware
Example usage of the Auth middleware
auth/quickstart command
Example usage of the Auth module for a quick start
Example usage of the Auth module for a quick start
auth/token_handling command
Example demonstrating the concept of token handling in authentication
Example demonstrating the concept of token handling in authentication
auth/user_info command
Example demonstrating how to get user information from the context
Example demonstrating how to get user information from the context
cache/basic_usage command
Example demonstrating basic usage of the cache package
Example demonstrating basic usage of the cache package
cache/custom_configuration command
Example demonstrating custom configuration of the cache package
Example demonstrating custom configuration of the cache package
circuit/basic_usage command
Example demonstrating basic usage of the circuit package
Example demonstrating basic usage of the circuit package
circuit/custom_configuration command
Example demonstrating custom configuration of the circuit package
Example demonstrating custom configuration of the circuit package
config/app_config command
Example of implementing and using the AppConfig interface
Example of implementing and using the AppConfig interface
config/basic_usage command
Example of basic usage of the config package
Example of basic usage of the config package
config/custom_adapter command
Example of creating a custom adapter for the config package
Example of creating a custom adapter for the config package
config/database_config command
Example of implementing and using the DatabaseConfig interface
Example of implementing and using the DatabaseConfig interface
context
Example of error handling with the context package
Example of error handling with the context package
context/basic_usage command
Example of basic usage of the context package
Example of basic usage of the context package
context/timeout command
Example of using timeouts with the context package
Example of using timeouts with the context package
context/value_propagation command
Example of value propagation with the context package
Example of value propagation with the context package
date/basic_usage command
Example of basic usage of the date package
Example of basic usage of the date package
date/error_handling command
Example of error handling with the date package
Example of error handling with the date package
date/optional_date command
Example of working with optional dates using the date package
Example of working with optional dates using the date package
date/time_zone command
Example of working with time zones using the date package
Example of working with time zones using the date package
db/connection command
Example of connecting to different database types
Example of connecting to different database types
db/health_check command
Example of checking database health
Example of checking database health
db/query command
Example of executing queries with different database types
Example of executing queries with different database types
db/repository command
Example of implementing the repository pattern with the db package
Example of implementing the repository pattern with the db package
db/retry command
Example of executing queries with retries
Example of executing queries with retries
db/transaction command
Example of using transactions with different database types
Example of using transactions with different database types
di/basic_usage command
Example of basic usage of the dependency injection package
Example of basic usage of the dependency injection package
di/generic_container command
Example of using the generic container from the dependency injection package
Example of using the generic container from the dependency injection package
di/service_container command
Example of using the service container from the dependency injection package
Example of using the service container from the dependency injection package
errors/basic_error_creation command
This example demonstrates how to create different types of errors using the errors package.
This example demonstrates how to create different types of errors using the errors package.
errors/error_categorization command
This example demonstrates how to categorize and handle different types of errors.
This example demonstrates how to categorize and handle different types of errors.
errors/error_context command
This example demonstrates how to add and retrieve context information from errors.
This example demonstrates how to add and retrieve context information from errors.
errors/error_wrapping command
This example demonstrates how to wrap errors to add context as they propagate up the call stack.
This example demonstrates how to wrap errors to add context as they propagate up the call stack.
errors/stack_traces command
This example demonstrates how to include and retrieve caller information from errors.
This example demonstrates how to include and retrieve caller information from errors.
graphql/authorization command
Example demonstrating how to check authorization in GraphQL operations
Example demonstrating how to check authorization in GraphQL operations
graphql/directive_registration command
Example demonstrating how to register the @isAuthorized directive in a GraphQL server
Example demonstrating how to register the @isAuthorized directive in a GraphQL server
graphql/jwt_token_generation command
Example demonstrating how to generate JWT tokens for testing GraphQL RBAC
Example demonstrating how to generate JWT tokens for testing GraphQL RBAC
graphql/resolver_authorization command
Example demonstrating how to check authorization in a GraphQL resolver
Example demonstrating how to check authorization in a GraphQL resolver
health/basic_usage command
Example of basic usage of the health package
Example of basic usage of the health package
health/custom_health_status command
Example of creating a custom health status response
Example of creating a custom health status response
logging/basic_usage command
Example of basic usage of the logging package
Example of basic usage of the logging package
logging/context_aware_logging command
Example of context-aware logging
Example of context-aware logging
logging/trace_id command
Example of adding trace IDs to logs
Example of adding trace IDs to logs
middleware/basic_usage command
Example of basic usage of the middleware package
Example of basic usage of the middleware package
middleware/cors command
Example of using the CORS middleware
Example of using the CORS middleware
middleware/error_handling command
Example of using the error handling middleware
Example of using the error handling middleware
middleware/logging command
Example of using the logging middleware
Example of using the logging middleware
middleware/recovery command
Example of using the recovery middleware
Example of using the recovery middleware
middleware/timeout command
Example of using the timeout middleware
Example of using the timeout middleware
rate/basic_usage command
Example demonstrating basic usage of the rate package
Example demonstrating basic usage of the rate package
rate/custom_configuration command
Example demonstrating custom configuration of the rate package
Example demonstrating custom configuration of the rate package
repository/basic_repository_example command
Example of basic repository implementation
Example of basic repository implementation
repository/dependency_injection_example command
Example of integration with dependency injection
Example of integration with dependency injection
repository/repository_factory_example command
Example of using repository factory
Example of using repository factory
retry/basic_usage command
Example demonstrating basic usage of the retry package
Example demonstrating basic usage of the retry package
retry/custom_configuration command
Example demonstrating custom configuration of the retry package
Example demonstrating custom configuration of the retry package
retry/error_detection command
Example demonstrating custom error detection with the retry package
Example demonstrating custom error detection with the retry package
retry/logging_tracing command
Example demonstrating logging and tracing with the retry package
Example demonstrating logging and tracing with the retry package
shutdown/basic_usage_example command
Example of basic graceful shutdown
Example of basic graceful shutdown
shutdown/multiple_resource_example command
Example of shutting down multiple resources
Example of shutting down multiple resources
shutdown/programmatic_shutdown_example command
Example of programmatic shutdown initiation
Example of programmatic shutdown initiation
signal/basic_signal_handling_example command
Example of basic signal handling
Example of basic signal handling
signal/manual_cancellation_example command
Example of manual cancellation with HandleShutdown
Example of manual cancellation with HandleShutdown
signal/shutdown_callbacks_example command
Example of using shutdown callbacks
Example of using shutdown callbacks
telemetry/http_instrumentation_example command
Example of using HTTP instrumentation in the telemetry package
Example of using HTTP instrumentation in the telemetry package
telemetry/initialization_example command
Example of initializing the telemetry package
Example of initializing the telemetry package
telemetry/metrics_example command
Example of using metrics functionality in the telemetry package
Example of using metrics functionality in the telemetry package
telemetry/prometheus_integration_example command
Example of integrating with Prometheus in the telemetry package
Example of integrating with Prometheus in the telemetry package
telemetry/tracing_example command
Example of using tracing functionality in the telemetry package
Example of using tracing functionality in the telemetry package
transaction/basic_saga_example command
Example of basic saga transaction
Example of basic saga transaction
transaction/basic_usage_example command
Example of basic usage of the transaction package with WithTransaction function
Example of basic usage of the transaction package with WithTransaction function
transaction/context_timeout_example command
Example of using context with timeout in transactions
Example of using context with timeout in transactions
transaction/custom_transaction_example command
Example of custom transaction execution
Example of custom transaction execution
transaction/error_handling_example command
Example of error handling with checked rollbacks
Example of error handling with checked rollbacks
transaction/idempotent_operations_example command
Example of idempotent operations in transactions
Example of idempotent operations in transactions
validation/basic_validation_example command
Example of basic validation using the validation package
Example of basic validation using the validation package
validation/collection_validation_example command
Example of collection validation using the validation package
Example of collection validation using the validation package
validation/custom_validation_example command
Example of custom validation using the validation package
Example of custom validation using the validation package
validation/date_validation_example command
Example of date validation using the validation package
Example of date validation using the validation package
valueobject/appearance/color_example command
Example usage of the Color value object
Example usage of the Color value object
valueobject/base/base_example command
Example usage of the base value object types
Example usage of the base value object types
valueobject/contact/email_example command
Example usage of the Email value object
Example usage of the Email value object
valueobject/identification/id_example command
Example usage of the ID value object
Example usage of the ID value object
valueobject/identification/username_example command
Example usage of the Username value object
Example usage of the Username value object
valueobject/location/coordinate_example command
Example usage of the Coordinate value object
Example usage of the Coordinate value object
valueobject/measurement/filesize_example command
Example usage of the FileSize value object
Example usage of the FileSize value object
valueobject/measurement/money_example command
Example usage of the Money value object
Example usage of the Money value object
valueobject/network/ipaddress_example command
Example usage of the IPAddress value object
Example usage of the IPAddress value object
valueobject/network/url_example command
Example usage of the URL value object
Example usage of the URL value object
valueobject/temporal/time_example command
Example usage of the Time value object
Example usage of the Time value object
Package auth provides authentication and authorization functionality.
Package auth provides authentication and authorization functionality.
config
Package config provides adapters for auth configuration.
Package config provides adapters for auth configuration.
errors
Package errors provides comprehensive error handling for the auth module.
Package errors provides comprehensive error handling for the auth module.
jwt
Package jwt provides JWT token handling for the auth module.
Package jwt provides JWT token handling for the auth module.
middleware
Package middleware provides HTTP middleware for authentication.
Package middleware provides HTTP middleware for authentication.
oidc
Package oidc provides OpenID Connect integration for the auth module.
Package oidc provides OpenID Connect integration for the auth module.
service
Package service provides authorization services for the auth module.
Package service provides authorization services for the auth module.
Package cache provides functionality for caching frequently accessed data.
Package cache provides functionality for caching frequently accessed data.
Package circuit provides functionality for circuit breaking on external dependencies.
Package circuit provides functionality for circuit breaking on external dependencies.
Package config provides generic configuration interfaces and adapters.
Package config provides generic configuration interfaces and adapters.
interfaces
Package interfaces provides generic configuration interfaces that can be used across different applications.
Package interfaces provides generic configuration interfaces that can be used across different applications.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package context provides utilities for working with Go's context package.
Package context provides utilities for working with Go's context package.
Package date provides utilities for working with dates and times.
Package date provides utilities for working with dates and times.
db
Package db provides utilities for working with databases.
Package db provides utilities for working with databases.
interfaces
Package interfaces provides database interfaces for the db package.
Package interfaces provides database interfaces for the db package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
di
Package di provides a generic dependency injection container that can be used across different applications.
Package di provides a generic dependency injection container that can be used across different applications.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package env provides utilities for working with environment variables.
Package env provides utilities for working with environment variables.
Package errors provides error handling utilities for the servicelib package.
Package errors provides error handling utilities for the servicelib package.
app
Package app provides application-level error types for the application.
Package app provides application-level error types for the application.
core
Package core provides the core error handling functionality for the application.
Package core provides the core error handling functionality for the application.
domain
Package domain provides domain-specific error types for the application.
Package domain provides domain-specific error types for the application.
http
Package http provides HTTP-related error utilities for the application.
Package http provides HTTP-related error utilities for the application.
infra
Package infra provides infrastructure-related error types for the application.
Package infra provides infrastructure-related error types for the application.
log
Package log provides logging integration for the error handling system.
Package log provides logging integration for the error handling system.
metrics
Package metrics provides metrics integration for the error handling system.
Package metrics provides metrics integration for the error handling system.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
trace
Package trace provides tracing integration for the error handling system.
Package trace provides tracing integration for the error handling system.
types
Package types provides specific error types for the errors package.
Package types provides specific error types for the errors package.
Package graphql provides utilities for working with GraphQL.
Package graphql provides utilities for working with GraphQL.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package health provides functionality for health checking the application.
Package health provides functionality for health checking the application.
Package logging provides centralized logging functionality for services.
Package logging provides centralized logging functionality for services.
interfaces
Package interfaces defines the interfaces for the logging package.
Package interfaces defines the interfaces for the logging package.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package model provides utilities for working with domain models and DTOs.
Package model provides utilities for working with domain models and DTOs.
Package rate provides functionality for rate limiting to protect resources.
Package rate provides functionality for rate limiting to protect resources.
Package repository provides generic repository interfaces for data persistence operations.
Package repository provides generic repository interfaces for data persistence operations.
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
Package retry provides functionality for retrying operations with configurable backoff and jitter.
Package retry provides functionality for retrying operations with configurable backoff and jitter.
Package shutdown provides functionality for graceful application shutdown.
Package shutdown provides functionality for graceful application shutdown.
Package signal provides utilities for handling OS signals and implementing graceful shutdown.
Package signal provides utilities for handling OS signals and implementing graceful shutdown.
Package stringutil provides additional string manipulation utilities beyond what's available in the standard library.
Package stringutil provides additional string manipulation utilities beyond what's available in the standard library.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
Package telemetry provides functionality for collecting and exporting telemetry data, including distributed tracing and metrics.
mocks
Package mocks contains mock implementations for telemetry package testing
Package mocks contains mock implementations for telemetry package testing
Package tools provides utility tools for development and maintenance of the servicelib project.
Package tools provides utility tools for development and maintenance of the servicelib project.
readme_fixer command
Package main provides a utility for fixing and standardizing README.md files.
Package main provides a utility for fixing and standardizing README.md files.
readme_validator command
Package main provides a utility for validating README.md files against templates.
Package main provides a utility for validating README.md files against templates.
Package transaction provides utilities for managing transactions in distributed systems.
Package transaction provides utilities for managing transactions in distributed systems.
saga
Package saga provides utilities for implementing the saga pattern for distributed transactions.
Package saga provides utilities for implementing the saga pattern for distributed transactions.
Package validation provides utilities for validating data in a structured and reusable way.
Package validation provides utilities for validating data in a structured and reusable way.
Package valueobject provides a comprehensive framework for implementing domain value objects.
Package valueobject provides a comprehensive framework for implementing domain value objects.
appearance
Package appearance provides value objects related to appearance information.
Package appearance provides value objects related to appearance information.
base
Package base provides the core interfaces and implementations for value objects.
Package base provides the core interfaces and implementations for value objects.
cmd/generate command
Package main provides a command-line tool for generating value objects.
Package main provides a command-line tool for generating value objects.
contact
Package contact provides value objects related to contact information.
Package contact provides value objects related to contact information.
generator
Package generator provides code generation tools for value objects.
Package generator provides code generation tools for value objects.
identification
Package identification provides value objects related to identification.
Package identification provides value objects related to identification.
location
Package location provides value objects related to location information.
Package location provides value objects related to location information.
measurement
Package measurement provides value objects related to measurement information.
Package measurement provides value objects related to measurement information.
network
Package network provides value objects related to network information.
Package network provides value objects related to network information.
temporal
Package temporal provides immutable value objects for representing and manipulating temporal concepts such as dates, times, durations, and versions.
Package temporal provides immutable value objects for representing and manipulating temporal concepts such as dates, times, durations, and versions.

Jump to

Keyboard shortcuts

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