servicelib

module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2025 License: MIT

README

ServiceLib

codecov Go Report Card GoDoc

Overview

Note: The Family-Service repository implements a GraphQL service using ServiceLib. It serves as an excellent illustration of ServiceLib's capabilities and potential.

ServiceLib is a comprehensive Go library designed to accelerate the development of robust, production-ready microservices. It provides a collection of reusable components and utilities that address common challenges in service development, allowing developers to focus on business logic rather than infrastructure concerns.

The library follows modern Go practices and design patterns, with a focus on:

  • Modularity: Each component can be used independently or together with others
  • Testability: All components are designed with testing in mind
  • Performance: Optimized for high-throughput microservices
  • Reliability: Built-in error handling and recovery mechanisms
  • Observability: Integrated logging, metrics, and tracing

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
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 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