go-project-template

module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2026 License: MIT

README ΒΆ

πŸš€ Go Project Template

A production-ready Go project template following Clean Architecture and Domain-Driven Design principles, optimized for building scalable applications with PostgreSQL or MySQL.

CI Go Report Card

✨ Features

  • πŸ—οΈ Clean Architecture - Clear separation of concerns with domain, repository, use case, and presentation layers
  • πŸ“¦ Modular Domain Structure - Easy to add new domains without affecting existing code
  • πŸ”Œ Dependency Injection - Centralized component wiring with lazy initialization
  • πŸ—„οΈ Multi-Database Support - PostgreSQL and MySQL with dedicated repository implementations
  • πŸ”„ Database Migrations - Separate migrations for PostgreSQL and MySQL
  • πŸ†” UUIDv7 Primary Keys - Time-ordered, globally unique identifiers
  • πŸ’Ό Transaction Management - Built-in support for database transactions
  • πŸ“¬ Transactional Outbox Pattern - Event-driven architecture with guaranteed delivery
  • ⚠️ Standardized Error Handling - Domain errors with proper HTTP status code mapping
  • βœ… Input Validation - Advanced validation with custom rules (email, password strength, etc.)
  • πŸ”’ Password Hashing - Secure Argon2id password hashing
  • πŸ§ͺ Integration Testing - Real database tests instead of mocks
  • 🐳 Docker Support - Multi-stage Dockerfile and Docker Compose setup
  • 🚦 CI/CD Ready - GitHub Actions workflow with comprehensive testing
  • πŸ“Š Structured Logging - JSON logs using slog
  • πŸ› οΈ Comprehensive Makefile - Easy development and deployment commands

πŸ“š Documentation

  • πŸ“– Getting Started - Installation and setup guide
  • πŸ—οΈ Architecture - Architectural patterns and design principles
  • πŸ› οΈ Development - Development workflow and coding standards
  • πŸ§ͺ Testing - Testing strategies and best practices
  • ⚠️ Error Handling - Error handling system guide
  • βž• Adding Domains - Step-by-step guide to add new domains

πŸš€ Quick Start

Prerequisites
  • Go 1.25+
  • PostgreSQL 12+ or MySQL 8.0+
  • Docker and Docker Compose (optional)
Installation
# Clone the repository
git clone https://github.com/allisson/go-project-template.git
cd go-project-template

# Install dependencies
go mod download

# Start a database (using Docker)
make dev-postgres  # or make dev-mysql

# Run migrations
make run-migrate

# Start the server
make run-server

The server will be available at http://localhost:8080

For detailed setup instructions, see the Getting Started Guide.

πŸ“– Project Structure

go-project-template/
β”œβ”€β”€ cmd/app/                    # Application entry point
β”œβ”€β”€ internal/
β”‚   β”œβ”€β”€ app/                    # Dependency injection container
β”‚   β”œβ”€β”€ config/                 # Configuration management
β”‚   β”œβ”€β”€ database/               # Database connection and transactions
β”‚   β”œβ”€β”€ errors/                 # Standardized domain errors
β”‚   β”œβ”€β”€ http/                   # HTTP server infrastructure
β”‚   β”œβ”€β”€ httputil/               # HTTP utilities (JSON responses, error mapping)
β”‚   β”œβ”€β”€ validation/             # Custom validation rules
β”‚   β”œβ”€β”€ testutil/               # Test utilities
β”‚   β”œβ”€β”€ user/                   # User domain module
β”‚   β”‚   β”œβ”€β”€ domain/             # User entities and domain errors
β”‚   β”‚   β”œβ”€β”€ usecase/            # User business logic
β”‚   β”‚   β”œβ”€β”€ repository/         # User data access
β”‚   β”‚   └── http/               # User HTTP handlers and DTOs
β”‚   └── outbox/                 # Outbox domain module
β”‚       β”œβ”€β”€ domain/             # Outbox entities and domain errors
β”‚       β”œβ”€β”€ usecase/            # Outbox event processing logic
β”‚       └── repository/         # Outbox data access
β”œβ”€β”€ migrations/
β”‚   β”œβ”€β”€ postgresql/             # PostgreSQL migrations
β”‚   └── mysql/                  # MySQL migrations
β”œβ”€β”€ docs/                       # Documentation
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ Makefile
└── docker-compose.test.yml

Learn more about the architecture in the Architecture Guide.

πŸ§ͺ Testing

# Start test databases
make test-db-up

# Run all tests
make test

# Run tests with coverage
make test-coverage

# Stop test databases
make test-db-down

# Or run everything in one command
make test-with-db

The project uses real PostgreSQL and MySQL databases for testing instead of mocks. See the Testing Guide for details.

πŸ› οΈ Development

Build Commands
make build                    # Build the application
make run-server              # Run HTTP server
make run-worker              # Run outbox event processor
make run-migrate             # Run database migrations
make lint                    # Run linter with auto-fix
make clean                   # Clean build artifacts
API Endpoints
Health Check
curl http://localhost:8080/health
Register User
curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "SecurePass123!"
  }'

For more development workflows, see the Development Guide.

πŸ”‘ Key Concepts

Clean Architecture Layers
  • Domain Layer 🎯 - Business entities and rules (pure, no external dependencies)
  • Repository Layer πŸ’Ύ - Data persistence (separate MySQL and PostgreSQL implementations)
  • Use Case Layer πŸ’Ό - Business logic and orchestration
  • Presentation Layer 🌐 - HTTP handlers and DTOs
  • Utility Layer πŸ› οΈ - Shared utilities (error handling, validation, HTTP helpers)
Error Handling System

The project uses a standardized error handling system:

  • Standard Errors: ErrNotFound, ErrConflict, ErrInvalidInput, ErrUnauthorized, ErrForbidden
  • Domain Errors: Wrap standard errors with domain-specific context
  • Automatic HTTP Mapping: Domain errors automatically map to appropriate HTTP status codes

Example:

// Define domain error
var ErrUserNotFound = errors.Wrap(errors.ErrNotFound, "user not found")

// Use in repository
if errors.Is(err, sql.ErrNoRows) {
    return nil, domain.ErrUserNotFound  // Maps to 404 Not Found
}

Learn more in the Error Handling Guide.

UUIDv7 Primary Keys

All entities use UUIDv7 for primary keys:

  • ⏱️ Time-ordered for better database performance
  • 🌍 Globally unique across distributed systems
  • πŸ“Š Better than UUIDv4 for database indexes
Transactional Outbox Pattern

Ensures reliable event delivery using a use case-based approach:

  1. Business operation and event stored in same transaction
  2. Outbox use case processes pending events with configurable retry logic
  3. Guarantees at-least-once delivery
  4. Extensible event processing via the EventProcessor interface

🐳 Docker

# Build Docker image
make docker-build

# Run server in Docker
make docker-run-server

# Run worker in Docker
make docker-run-worker

# Run migrations in Docker
make docker-run-migrate

The worker command runs the outbox event processor, which handles asynchronous event processing using the transactional outbox pattern.

πŸ”§ Configuration

All configuration is done via environment variables. Create a .env file in your project root:

DB_DRIVER=postgres
DB_CONNECTION_STRING=postgres://user:password@localhost:5432/mydb?sslmode=disable
SERVER_HOST=0.0.0.0
SERVER_PORT=8080
LOG_LEVEL=info

See the Getting Started Guide for all available configuration options.

βž• Adding New Domains

Adding a new domain is straightforward:

  1. Create domain structure (domain/, usecase/, repository/, http/)
  2. Define domain entity and errors
  3. Create database migrations
  4. Implement repositories (PostgreSQL and MySQL)
  5. Implement use case with business logic
  6. Create DTOs and HTTP handlers
  7. Register in DI container
  8. Wire HTTP routes

See the Adding Domains Guide for a complete step-by-step tutorial.

πŸ“¦ Dependencies

Core Libraries
Database Drivers

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

This template leverages these excellent Go libraries:

  • github.com/allisson/go-env
  • github.com/allisson/go-pwdhash
  • github.com/jellydator/validation
  • github.com/google/uuid
  • github.com/urfave/cli
  • github.com/golang-migrate/migrate

Built with ❀️ by Allisson

Directories ΒΆ

Path Synopsis
cmd
app command
Package main provides the entry point for the application with CLI commands.
Package main provides the entry point for the application with CLI commands.
internal
app
Package app provides dependency injection container for assembling application components.
Package app provides dependency injection container for assembling application components.
config
Package config provides application configuration management through environment variables.
Package config provides application configuration management through environment variables.
database
Package database provides database connection management and configuration.
Package database provides database connection management and configuration.
errors
Package errors provides standardized domain errors that express business intent rather than infrastructure details.
Package errors provides standardized domain errors that express business intent rather than infrastructure details.
http
Package http provides HTTP server implementation and request handlers.
Package http provides HTTP server implementation and request handlers.
httputil
Package httputil provides HTTP utility functions for request and response handling.
Package httputil provides HTTP utility functions for request and response handling.
outbox/domain
Package domain defines the core outbox domain entities and types.
Package domain defines the core outbox domain entities and types.
outbox/repository
Package repository provides data persistence implementations for outbox entities.
Package repository provides data persistence implementations for outbox entities.
outbox/usecase
Package usecase implements the outbox business logic and orchestrates outbox domain operations.
Package usecase implements the outbox business logic and orchestrates outbox domain operations.
user/domain
Package domain defines the core user domain entities and types.
Package domain defines the core user domain entities and types.
user/http
Package http provides HTTP handlers for user-related operations.
Package http provides HTTP handlers for user-related operations.
user/http/dto
Package dto provides data transfer objects for the user HTTP layer.
Package dto provides data transfer objects for the user HTTP layer.
user/repository
Package repository provides data persistence implementations for user entities.
Package repository provides data persistence implementations for user entities.
user/usecase
Package usecase implements the user business logic and orchestrates user domain operations.
Package usecase implements the user business logic and orchestrates user domain operations.
validation
Package validation provides custom validation rules for the application.
Package validation provides custom validation rules for the application.

Jump to

Keyboard shortcuts

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