{"id":37183269,"url":"https://github.com/ranchocooper/go-hexagonal","last_synced_at":"2026-01-14T21:09:51.206Z","repository":{"id":43727766,"uuid":"433284170","full_name":"RanchoCooper/go-hexagonal","owner":"RanchoCooper","description":"Go Hexagonal Architecture: Enterprise-grade Hexagonal Architectur Framework","archived":false,"fork":false,"pushed_at":"2025-09-29T09:34:12.000Z","size":15676,"stargazers_count":39,"open_issues_count":2,"forks_count":13,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-29T11:34:20.918Z","etag":null,"topics":["clean-architecture","ddd","hexagonal-architecture","template-project"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RanchoCooper.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2021-11-30T03:49:37.000Z","updated_at":"2025-09-29T09:34:13.000Z","dependencies_parsed_at":"2024-06-03T09:43:27.165Z","dependency_job_id":"8adb59a2-1a3b-4af7-b741-7b4f611b43f0","html_url":"https://github.com/RanchoCooper/go-hexagonal","commit_stats":{"total_commits":80,"total_committers":2,"mean_commits":40.0,"dds":0.0625,"last_synced_commit":"0b6497e720b24b67a6a3c73ec17558c3d57b4f40"},"previous_names":[],"tags_count":4,"template":true,"template_full_name":null,"purl":"pkg:github/RanchoCooper/go-hexagonal","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RanchoCooper%2Fgo-hexagonal","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RanchoCooper%2Fgo-hexagonal/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RanchoCooper%2Fgo-hexagonal/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RanchoCooper%2Fgo-hexagonal/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RanchoCooper","download_url":"https://codeload.github.com/RanchoCooper/go-hexagonal/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RanchoCooper%2Fgo-hexagonal/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28434586,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T18:57:19.464Z","status":"ssl_error","status_checked_at":"2026-01-14T18:52:48.501Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["clean-architecture","ddd","hexagonal-architecture","template-project"],"created_at":"2026-01-14T21:09:50.465Z","updated_at":"2026-01-14T21:09:51.197Z","avatar_url":"https://github.com/RanchoCooper.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Go Hexagonal Architecture\n\nWelcome to visit my [blog post](https://blog.ranchocooper.com/2025/03/20/go-hexagonal/)\n\n\n![CI Status](https://github.com/RanchoCooper/go-hexagonal/actions/workflows/ci.yaml/badge.svg)\n[![codecov](https://codecov.io/gh/RanchoCooper/go-hexagonal/branch/master/graph/badge.svg)](https://codecov.io/gh/RanchoCooper/go-hexagonal)\n\n\n![Hexagonal Architecture](https://github.com/Sairyss/domain-driven-hexagon/raw/master/assets/images/DomainDrivenHexagon.png)\n\n## Project Overview\n\nThis project is a Go microservice framework based on [Hexagonal Architecture](https://en.wikipedia.org/wiki/Hexagonal_architecture_(software)) and [Domain-Driven Design](https://en.wikipedia.org/wiki/Domain-driven_design). It provides a clear project structure and design patterns to help developers build maintainable, testable, and scalable applications.\n\nHexagonal Architecture (also known as [Ports and Adapters Architecture](https://en.wikipedia.org/wiki/Hexagonal_architecture_(software))) divides the application into internal and external parts, implementing [Separation of Concerns](https://en.wikipedia.org/wiki/Separation_of_concerns) and [Dependency Inversion Principle](https://en.wikipedia.org/wiki/Dependency_inversion_principle) through well-defined interfaces (ports) and implementations (adapters). This architecture decouples business logic from technical implementation details, facilitating unit testing and feature extension.\n\n## Core Features\n\n### Architecture Design\n- **[Domain-Driven Design (DDD)](https://en.wikipedia.org/wiki/Domain-driven_design)** - Organize business logic through concepts like [Aggregates](https://en.wikipedia.org/wiki/Domain-driven_design), [Entities](https://en.wikipedia.org/wiki/Entity), and [Value Objects](https://en.wikipedia.org/wiki/Value_object)\n- **[Hexagonal Architecture](https://en.wikipedia.org/wiki/Hexagonal_architecture_(software))** - Divide the application into domain, application, and adapter layers\n- **[Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection)** - Use [Wire](https://github.com/google/wire) for dependency injection, improving code testability and flexibility\n- **[Repository Pattern](https://en.wikipedia.org/wiki/Repository_pattern)** - Abstract data access layer with transaction support\n- **[Domain Events](https://en.wikipedia.org/wiki/Domain-driven_design)** - Implement [Event-Driven Architecture](https://en.wikipedia.org/wiki/Event-driven_architecture), supporting loosely coupled communication between system components\n- **[CQRS Pattern](https://en.wikipedia.org/wiki/Command_Query_Responsibility_Segregation)** - Command and Query Responsibility Segregation, optimizing read and write operations\n- **[Interface-Driven Design](https://en.wikipedia.org/wiki/Interface-based_programming)** - Use interfaces to define service contracts, implementing Dependency Inversion Principle\n\n### Technical Implementation\n- **[RESTful API](https://en.wikipedia.org/wiki/Representational_state_transfer)** - Implement HTTP API using the [Gin](https://github.com/gin-gonic/gin) framework\n- **Database Support** - Integrate [GORM](https://gorm.io) with support for [MySQL](https://en.wikipedia.org/wiki/MySQL), [PostgreSQL](https://en.wikipedia.org/wiki/PostgreSQL), and other databases\n- **Cache Support** - Integrate [Redis](https://en.wikipedia.org/wiki/Redis) caching with comprehensive error handling, local error definitions for cache misses, and health check implementation for monitoring cache availability\n- **Enhanced Cache** - Advanced cache features including negative caching to prevent cache penetration, distributed locking for cache consistency, and key tracking for improved hit rates\n- **MongoDB Support** - Integration with MongoDB for document storage\n- **Logging System** - Use [Zap](https://go.uber.org/zap) for high-performance logging with structured context support for tracing and debugging\n- **Configuration Management** - Use [Viper](https://github.com/spf13/viper) for flexible configuration management\n- **[Graceful Shutdown](https://en.wikipedia.org/wiki/Graceful_exit)** - Support graceful service startup and shutdown\n- **[Unit Testing](https://en.wikipedia.org/wiki/Unit_testing)** - Use [go-sqlmock](https://github.com/DATA-DOG/go-sqlmock), [redismock](https://github.com/go-redis/redismock), and [testify/mock](https://github.com/stretchr/testify) for comprehensive test coverage with enhanced HTTP testing utilities and improved DTO handling\n- **Transaction Support** - Provide no-operation transaction implementation, simplifying service layer interaction with repository layer, complete with mock transaction implementation and lifecycle hooks (Begin, Commit, and Rollback) for testing\n- **Asynchronous Event Processing** - Support for asynchronous event handling with worker pools, event persistence, and replay capabilities\n\n### Development Toolchain\n- **Code Quality** - Integrate [Golangci-lint](https://github.com/golangci/golangci-lint) for code quality checks\n- **Commit Standards** - Use [Commitlint](https://github.com/conventional-changelog/commitlint) to ensure Git commit messages follow conventions\n- **Pre-commit Hooks** - Use [Pre-commit](https://pre-commit.com) for code checking and formatting\n- **[CI/CD](https://en.wikipedia.org/wiki/CI/CD)** - Integrate [GitHub Actions](https://github.com/features/actions) for continuous integration and deployment\n\n## Recent Enhancements\n\n### Unified Error Handling\n- Extended error handling with consistent error types and error wrapping functions\n- Support for structured error details and HTTP status code mapping\n- Error comparison capabilities for more robust error checking\n\n### Enhanced Structured Logging\n- Context-aware logging with support for request IDs, user IDs, and trace IDs\n- Consistent log formatting and level management\n- Improved debugging capabilities with contextual information\n\n### Asynchronous Event System\n- Worker pool-based event processing for improved throughput\n- Event persistence and replay capabilities for reliability\n- Graceful shutdown support for event processing\n\n### Advanced Caching Features\n- Negative caching to protect against cache penetration\n- Distributed locking to prevent cache stampede\n- Key tracking for improved cache hit rates\n- Cache consistency mechanisms for data integrity\n\n### Dual-Mode HTTP Handlers\n- Flexible HTTP handlers that can work with both application layer factories and direct domain services\n- Support for direct service calls in testing and simpler use cases\n- Improved testability with better converter integration for request/response transformations\n- Graceful fallback to application factory mode when direct service mode is not available\n- Enhanced testing capabilities with simplified mock setup\n\n### Comprehensive Monitoring and Observability\n- Prometheus metrics collection for all layers of the application\n- HTTP request tracking with duration, status codes, and error rates\n- Database operation monitoring with query duration and error counts\n- Transaction performance metrics with operation tracking\n- Cache performance monitoring with hit/miss ratios\n- Domain event monitoring for business process insights\n- Customizable metrics endpoints with health check support\n\n## Project Structure\n\n```\n.\n├── adapter/                # Adapter Layer - External system interactions\n│   ├── amqp/               # Message queue adapters\n│   ├── dependency/         # Dependency injection configuration\n│   │   └── wire.go         # Wire DI setup with interface bindings\n│   ├── job/                # Scheduled task adapters\n│   └── repository/         # Data repository adapters\n│       ├── mysql/          # MySQL implementation\n│       │   └── entity/     # Database entities and repo implementations\n│       ├── postgre/        # PostgreSQL implementation\n│       ├── mongo/          # MongoDB implementation\n│       └── redis/          # Redis implementation\n│           └── enhanced_cache.go  # Enhanced cache with advanced features\n├── api/                    # API Layer - HTTP requests and responses\n│   ├── dto/                # Data Transfer Objects for API\n│   ├── error_code/         # Error code definitions\n│   ├── grpc/               # gRPC API handlers\n│   ├── middleware/         # Global middleware including metrics collection\n│   └── http/               # HTTP API handlers\n│       ├── handle/         # Request handlers using domain interfaces\n│       ├── middleware/     # HTTP middleware\n│       ├── paginate/       # Pagination handling\n│       └── validator/      # Request validation\n├── application/            # Application Layer - Use cases coordinating domain objects\n│   ├── core/               # Core interfaces and base implementations\n│   │   └── interfaces.go   # UseCase and UseCaseHandler interfaces\n│   └── example/            # Example use case implementations\n│       ├── create_example.go     # Create example use case\n│       ├── delete_example.go     # Delete example use case\n│       ├── get_example.go        # Get example use case\n│       ├── update_example.go     # Update example use case\n│       └── find_example_by_name.go # Find example by name use case\n├── cmd/                    # Command-line entry points\n│   └── main.go             # Main application entry point\n├── config/                 # Configuration management\n│   ├── config.go           # Configuration structure and loading\n│   └── config.yaml         # Configuration file\n├── domain/                 # Domain Layer - Core business logic\n│   ├── aggregate/          # Domain aggregates\n│   ├── dto/                # Domain Data Transfer Objects\n│   ├── event/              # Domain events\n│   ├── model/              # Domain models\n│   ├── repo/               # Repository interfaces\n│   ├── service/            # Domain services\n│   └── vo/                 # Value Objects\n└── tests/                  # Test utilities and examples\n    ├── migrations/         # Database migrations for testing\n    ├── mysql.go            # MySQL test utilities\n    ├── postgresql.go       # PostgreSQL test utilities\n    └── redis.go            # Redis test utilities\n```\n\n## Architecture Design Principles\n\n### Layer Separation\n1. **Domain Layer** (`domain/`)\n   - Contains core business logic and rules\n   - Defines domain models, aggregates, and value objects\n   - Declares repository interfaces and domain services\n   - Independent of external concerns\n\n2. **Application Layer** (`application/`)\n   - Implements use cases and orchestrates domain objects\n   - Handles transaction boundaries\n   - Coordinates between domain objects and external systems\n   - Contains no business rules\n\n3. **Adapter Layer** (`adapter/`)\n   - Implements interfaces defined by domain and application layers\n   - Handles external concerns (databases, HTTP, messaging)\n   - Provides concrete implementations of ports\n   - Contains technical details and frameworks\n\n4. **API Layer** (`api/`)\n   - Handles HTTP/gRPC requests and responses\n   - Manages data transformation between DTOs and domain objects\n   - Implements API-specific validation and error handling\n   - Provides API documentation and versioning\n\n### Key Architectural Elements\n\nThis structure enforces the Hexagonal Architecture principles:\n\n1. **Interface-Implementation Separation**:\n   - Domain layer defines interfaces (ports)\n   - Adapter layer provides implementations (adapters)\n   - Dependency flows inward, with outer layers depending on inner layers\n\n2. **Dependency Inversion**:\n   - High-level modules (domain/application) depend on abstractions\n   - Low-level modules (adapters) implement these abstractions\n   - All dependencies are injected through interfaces\n\n3. **Domain-Centric Design**:\n   - Domain models are pure business entities without technical concerns\n   - Repository interfaces declare what the domain needs\n   - Service interfaces define business operations\n\n4. **Clean Boundaries**:\n   - Each layer has clear responsibilities and dependencies\n   - Data transformation occurs at layer boundaries\n   - No leakage of implementation details between layers\n\n### Design Patterns and Principles\n\n1. **Dependency Inversion**\n   - High-level modules define interfaces\n   - Low-level modules implement interfaces\n   - Dependencies point inward toward the domain\n\n2. **Interface Segregation**\n   - Interfaces are specific to use cases\n   - Clients only depend on methods they use\n   - Prevents interface pollution\n\n3. **Single Responsibility**\n   - Each component has one reason to change\n   - Clear separation of concerns\n   - Focused and maintainable code\n\n4. **Open/Closed**\n   - Open for extension\n   - Closed for modification\n   - New features through new implementations\n\n## Architecture Layers\n\n### Domain Layer\nThe domain layer is the core of the application, containing business logic and rules. It is independent of other layers and does not depend on any external components.\n\n- **Models**: Domain entities and value objects\n  - `Example`: Example entity, containing basic properties like ID, name, alias, etc.\n\n- **Repository Interfaces**: Define data access interfaces\n  - `IExampleRepo`: Example repository interface, defining operations like create, read, update, delete, etc.\n  - `IExampleCacheRepo`: Example cache interface, defining health check methods\n  - `Transaction`: Transaction interface, supporting transaction begin, commit, and rollback\n\n- **Domain Services**: Handle business logic across entities\n  - `IExampleService`: Service interface defining contracts for example-related operations\n  - `ExampleService`: Implementation of the example service interface, handling business logic for example entities\n\n- **Domain Events**: Define events within the domain\n  - `ExampleCreatedEvent`: Example creation event\n  - `ExampleUpdatedEvent`: Example update event\n  - `ExampleDeletedEvent`: Example deletion event\n  - `AsyncEventBus`: Asynchronous event processing with persistence\n\n### Application Layer\nThe application layer coordinates domain objects to complete specific application tasks. It depends on domain interfaces but not on concrete implementations, following the Dependency Inversion Principle.\n\n- **Use Cases**: Define application functionality\n  - `CreateExampleUseCase`: Create example use case\n  - `GetExampleUseCase`: Get example use case\n  - `UpdateExampleUseCase`: Update example use case\n  - `DeleteExampleUseCase`: Delete example use case\n  - `FindExampleByNameUseCase`: Find example by name use case\n\n- **Commands and Queries**: Implement CQRS pattern\n  - Each use case defines Input and Output structures, representing command/query inputs and results\n\n- **Event Handlers**: Process domain events\n  - `LoggingEventHandler`: Logging event handler, recording all events\n  - `ExampleEventHandler`: Example event handler, processing events related to examples\n\n### Adapter Layer\nThe adapter layer implements interaction with external systems, such as databases and message queues.\n\n- **Repository Implementation**: Implement data access interfaces\n  - `EntityExample`: MySQL implementation of example repository\n  - `NoopTransaction`: No-operation transaction implementation, simplifying testing\n  - `MySQL`: MySQL connection and transaction management\n  - `Redis`: Redis connection and basic operations\n  - `EnhancedCache`: Advanced Redis caching with anti-penetration protection\n\n- **Message Queue Adapters**: Implement message publishing and subscription\n  - Support for Kafka and other message queue integrations\n\n- **Scheduled Tasks**: Implement scheduled tasks\n  - Cron-based task scheduling system\n\n### API Layer\nThe API layer handles HTTP requests and responses, serving as the entry point to the application.\n\n- **Controllers**: Handle HTTP requests\n  - `CreateExample`: Create example API\n  - `GetExample`: Get example API\n  - `UpdateExample`: Update example API\n  - `DeleteExample`: Delete example API\n  - `FindExampleByName`: Find example by name API\n\n- **Middleware**: Implement cross-cutting concerns\n  - Internationalization support\n  - CORS support\n  - Request ID tracking\n  - Request logging\n\n- **Data Transfer Objects (DTOs)**: Define request and response data structures\n  - `CreateExampleReq`: Create example request\n  - `UpdateExampleReq`: Update example request\n  - `DeleteExampleReq`: Delete example request\n  - `GetExampleReq`: Get example request\n\n### Testing Strategy\n\n1. **Unit Testing**\n   - Domain logic tested in isolation\n   - Mock external dependencies\n   - Fast and reliable tests\n\n2. **Integration Testing**\n   - Test adapter implementations\n   - Verify external system interactions\n   - Database and cache testing\n\n3. **End-to-End Testing**\n   - Test complete use cases\n   - Verify system behavior\n   - API contract testing\n\n## Dependency Injection\n\nThis project uses Google Wire for dependency injection, organizing dependencies as follows:\n\n```go\n// Initialize services\nfunc InitializeServices(ctx context.Context) (*service.Services, error) {\n    wire.Build(\n        // Repository dependencies\n        entity.NewExample,\n        wire.Bind(new(repo.IExampleRepo), new(*entity.EntityExample)),\n\n        // Event bus dependencies\n        provideEventBus,\n        wire.Bind(new(event.EventBus), new(*event.InMemoryEventBus)),\n\n        // Service dependencies\n        provideExampleService,\n        wire.Bind(new(service.IExampleService), new(*service.ExampleService)),\n        provideServices,\n    )\n    return nil, nil\n}\n\n// Provide event bus\nfunc provideEventBus() *event.InMemoryEventBus {\n    eventBus := event.NewInMemoryEventBus()\n\n    // Register event handlers\n    loggingHandler := event.NewLoggingEventHandler()\n    exampleHandler := event.NewExampleEventHandler()\n    eventBus.Subscribe(loggingHandler)\n    eventBus.Subscribe(exampleHandler)\n\n    return eventBus\n}\n\n// Provide example service\nfunc provideExampleService(repo repo.IExampleRepo, eventBus event.EventBus) *service.ExampleService {\n    exampleService := service.NewExampleService(repo)\n    exampleService.EventBus = eventBus\n    return exampleService\n}\n\n// Provide services container\nfunc provideServices(exampleService service.IExampleService, eventBus event.EventBus) *service.Services {\n    return service.NewServices(exampleService, eventBus)\n}\n```\n\n## Domain Events\n\nThe project supports both synchronous and asynchronous event handling:\n\n### Synchronous Event Handling\n```go\n// Publish an event synchronously\nerr := eventBus.Publish(ctx, event.NewExampleCreatedEvent(example.ID, example.Name))\n```\n\n### Asynchronous Event Handling\n```go\n// Configure asynchronous event bus\nconfig := event.DefaultAsyncEventBusConfig()\nconfig.QueueSize = 1000\nconfig.WorkerCount = 10\nasyncEventBus := event.NewAsyncEventBus(config)\n\n// Publish an event asynchronously\nerr := asyncEventBus.Publish(ctx, event.NewExampleCreatedEvent(example.ID, example.Name))\n\n// Graceful shutdown\nerr := asyncEventBus.Close(5 * time.Second)\n```\n\n## Enhanced Caching\n\nThe enhanced caching system provides advanced features for robust caching:\n\n```go\n// Create an enhanced cache with default options\ncache := redis.NewEnhancedCache(redisClient, redis.DefaultCacheOptions())\n\n// Try to get a value with auto-loading if missing\nvar result MyData\nerr := cache.TryGetSet(ctx, \"key:123\", \u0026result, 30*time.Minute, func() (interface{}, error) {\n    // This only executes if the key is not in cache\n    return fetchDataFromDatabase()\n})\n\n// Use distributed lock to prevent concurrent operations\nerr := cache.WithLock(ctx, \"lock:resource\", func() error {\n    // This code is protected by a distributed lock\n    return updateSharedResource()\n})\n```\n\n## Error Handling\n\nThe error system provides a consistent way to handle and propagate errors:\n\n```go\n// Create a domain error\nif entity == nil {\n    return errors.New(errors.ErrorTypeNotFound, \"entity not found\")\n}\n\n// Wrap an error with additional context\nif err := repo.Save(entity); err != nil {\n    return errors.Wrapf(err, errors.ErrorTypePersistence, \"failed to save entity %d\", entity.ID)\n}\n\n// Check error types\nif errors.IsNotFoundError(err) {\n    // Handle not found case\n}\n```\n\n## Structured Logging\n\nThe logging system supports context-aware structured logging:\n\n```go\n// Create a log context\nlogCtx := log.NewLogContext().\n    WithRequestID(requestID).\n    WithUserID(userID).\n    WithOperation(\"CreateEntity\")\n\n// Log with context\nlogger.InfoContext(logCtx, \"Creating new entity\",\n    zap.Int(\"entity_id\", entity.ID),\n    zap.String(\"entity_name\", entity.Name))\n```\n\n## Project Improvements\n\nThe project has recently undergone the following improvements:\n\n### 1. Unified API Versions\n- **Problem**: The project had both v1 and v2 API versions, causing code duplication and maintenance difficulties\n- **Solution**:\n  - Unified API routes, placing all APIs under the `/api` path\n  - Retained the `/v2` path for backward compatibility\n  - Used application layer use cases to handle all requests, phasing out direct domain service calls\n\n### 2. Enhanced Dependency Injection\n- **Problem**: Wire dependency injection configuration had duplicate binding issues, causing generation failures\n- **Solution**:\n  - Refactored the `wire.go` file, removing duplicate binding definitions\n  - Used provider functions instead of direct bindings\n  - Added event handler registration logic\n\n### 3. Eliminated Global Variables\n- **Problem**: The project used global variables to store service instances, violating dependency injection principles\n- **Solution**:\n  - Removed global service variables\n  - Properly injected services via the Factory pattern\n  - Improved testability by making dependencies explicit\n\n### 4. Enhanced Architecture Validation\n- **Problem**: Architecture validation was manual and prone to errors\n- **Solution**:\n  - Implemented automated layer dependency checking\n  - Enforced strict architectural boundaries through code scanning\n  - Added validation to CI pipeline\n\n### 5. Graceful Shutdown\n- **Problem**: Application didn't handle shutdown gracefully, potentially causing data loss\n- **Solution**:\n  - Implemented a graceful shutdown mechanism for the server, ensuring all in-flight requests are completed before shutting down\n  - Added shutdown timeout settings to prevent the shutdown process from hanging indefinitely\n  - Improved signal handling, supporting SIGINT and SIGTERM signals\n\n### 6. Internationalization Support\n- **Problem**: The application lacked proper internationalization support\n- **Solution**:\n  - Added translation middleware for multi-language validation error messages\n  - Automatically selected appropriate language based on the Accept-Language header\n\n### 7. CORS Support\n- **Problem**: Cross-origin requests were not properly handled\n- **Solution**:\n  - Added CORS middleware to handle cross-origin requests\n  - Configured allowed origins, methods, headers, and credentials\n\n### 8. Debugging Tools\n- **Problem**: Diagnosis of performance issues in production was difficult\n- **Solution**:\n  - Integrated pprof performance analysis tools for diagnosing performance issues in production environments\n  - Can be enabled or disabled via configuration file\n\n### 9. Advanced Redis Integration\n- **Problem**: Redis implementation was limited and lacked proper connection management\n- **Solution**:\n  - Enhanced Redis client with proper connection pooling\n  - Added comprehensive health checks and monitoring\n  - Improved error handling and connection lifecycle management\n\n### 10. Structured Request Logging\n- **Problem**: API requests lacked proper logging, making debugging difficult\n- **Solution**:\n  - Implemented comprehensive request logging middleware\n  - Added request ID tracking for correlating logs\n  - Configured log levels based on status codes\n\n### 11. Unified Error Response Format\n- **Problem**: Error responses had inconsistent formats across the API\n- **Solution**:\n  - Standardized error response structure with code, message, and details\n  - Added documentation references to errors\n  - Implemented consistent HTTP status code mapping\n\nThese optimizations make the project more robust, maintainable, and provide a better development experience.\n\n## Getting Started\n\n### Prerequisites\n- Go 1.21 or later\n- Docker (for running dependencies)\n- Homebrew (for macOS users)\n- Node.js and npm (for commit linting)\n- pre-commit (for code quality checks)\n- golangci-lint (for code linting)\n\n### Installation\n\n#### 1. Clone the Repository\n```bash\ngit clone https://github.com/RanchoCooper/go-hexagonal.git\ncd go-hexagonal\n```\n\n#### 2. Initialize Development Environment (macOS)\nThe project includes a convenient init target in the Makefile to set up all required tools:\n\n```bash\n# Install and configure all required dependencies\nmake init\n```\n\nThis command installs:\n- Go (if not already installed)\n- Node.js and npm (for commit linting)\n- pre-commit hooks\n- golangci-lint\n- commitlint for ensuring commit message standards\n\n#### 3. Manual Installation (non-macOS)\nIf you're not using macOS or prefer manual setup:\n\n```bash\n# Install golangci-lint\n# See https://golangci-lint.run/usage/install/\n\n# Install pre-commit\npip install pre-commit\n\n# Install commitlint\nnpm install -g @commitlint/cli @commitlint/config-conventional\n\n# Set up pre-commit hooks\nmake pre-commit.install\n```\n\n### Development Workflow\n\n#### Code Formatting\n```bash\n# Format code according to Go standards\nmake fmt\n```\n\n#### Running Tests\n```bash\n# Run tests with race detection and coverage reporting\nmake test\n```\n\n#### Code Quality Checks\n```bash\n# Run linters to check code quality\nmake ci.lint\n```\n\n#### Run All Checks\n```bash\n# Run formatting, linting, and tests\nmake all\n```\n\n### Configuration\n1. Copy `config/config.yaml.example` to `config/config.yaml` (if applicable)\n2. Adjust configuration values as needed\n3. Environment variables can override config file values\n\n### Docker Setup (Optional)\nIf your project uses Docker for local development:\n\n```bash\n# Start the required services (MySQL, Redis, etc.)\ndocker-compose up -d\n\n# Stop services when done\ndocker-compose down\n```\n\n### Pre-commit Hooks Management\n\nThe project uses pre-commit hooks to ensure code quality before committing:\n\n```bash\n# Update pre-commit hooks to latest versions\nmake precommit.rehook\n```\n\n### Running the Application\n\n```bash\n# Run the application\ngo run cmd/main.go\n```\n\n## Extension Plans\n\n- **gRPC Support** - Add gRPC service implementation\n- **Monitoring Integration** - Integrate Prometheus monitoring\n\n## References\n\n- **Architecture**\n  - [Freedom DDD Framework](https://github.com/8treenet/freedom)\n  - [Hexagonal Architecture in Go](https://medium.com/@matiasvarela/hexagonal-architecture-in-go-cfd4e436faa3)\n  - [Dependency Injection in A Nutshell](https://appliedgo.net/di/)\n- **Project Standards**\n  - [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0)\n  - [Improving Your Go Project With pre-commit hooks](https://goangle.medium.com/golang-improving-your-go-project-with-pre-commit-hooks-a265fad0e02f)\n- **Code References**\n  - [Go CleanArch](https://github.com/roblaszczak/go-cleanarch)\n\n## Contributing\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'feat: add amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the [Apache 2.0 License](LICENSE).\nYou are free to use, modify, and distribute this software under the terms of the license.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Franchocooper%2Fgo-hexagonal","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Franchocooper%2Fgo-hexagonal","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Franchocooper%2Fgo-hexagonal/lists"}