Skip to content

LoopContext/go-modulith-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

58 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Go Modulith Template ๐Ÿš€

Tests Coverage Go License

This is a professional template for building Go applications following the Modulith pattern. It's designed to be scalable, maintainable, and easy to maintain, allowing evolution from a monolith to microservices without friction.

โœจ Key Features

  • ๐Ÿ—๏ธ Modular Architecture: Code organized by domains with decoupling through internal events.
  • ๐Ÿ“ฆ Registry Pattern: Manual, explicit dependency injection without magic for maximum control.
  • ๐Ÿ” gRPC & Protobuf: Typed and efficient communication with automatic code generation via buf.
  • ๐Ÿ—„๏ธ SQLC & Migrations: Type-safe data access and schema management with golang-migrate.
  • โš™๏ธ Flexible Configuration: Configuration system with precedence hierarchy (YAML > .env > system ENV vars > defaults) and source logging.
  • ๐Ÿ”„ Hot Reload: Smooth development with Air monitoring changes in code, configuration (.env, YAML) and resources.
  • ๐Ÿ”Œ WebSocket Real-Time: Bidirectional communication integrated with the event bus for real-time notifications.
  • ๐Ÿ‘ท Worker Process: Background process for asynchronous tasks, event consumers, and scheduled jobs.
  • ๐Ÿ” Secrets Management: Abstraction for secret management (env vars, Vault, AWS Secrets Manager).
  • ๐Ÿ“Š Complete Observability: Local stack with Jaeger, Prometheus, and Grafana for development and debugging.
  • ๐Ÿ“Š Optional GraphQL: Optional support with gqlgen for flexible and frontend-friendly APIs (subscriptions included).
  • ๐Ÿ“ง Notification System: Templates + extensible providers (SendGrid, Twilio, AWS SES/SNS).
  • ๐Ÿ”‘ Complete Auth: Passwordless login, sessions, refresh tokens, revocation, and profile management.
  • ๐Ÿ”— OAuth/Social Login: Authentication with Google, Facebook, GitHub, Apple, Microsoft, and Twitter/X.
  • ๐Ÿงช Mocking with gomock: Automatic generation of type-safe mocks for efficient unit testing.
  • ๐Ÿงช Test Utilities: Comprehensive testing utilities (internal/testutil) for integration tests, gRPC servers, event bus, and test registries.
  • ๐Ÿ›ก๏ธ Observability: Native integration with OpenTelemetry (Tracing & Metrics), Prometheus, and Health Checks with context handling.
  • โšก Error Handling: Domain error system with automatic mapping to gRPC codes.
  • ๐Ÿ“ก Telemetry Helpers: Integrated helpers for consistent tracing across all modules.
  • ๐ŸŽฏ Typed Events: Typed constants for events with autocomplete and typo prevention.
  • ๐Ÿ”„ Multi-Module Migrations: Automatic discovery and execution of migrations per module.
  • ๐Ÿ” RBAC Built-in: Authorization helpers for permissions, roles, and ownership.
  • โ›ด๏ธ Cloud Ready: Multi-stage Dockerfile and flexible Helm Charts for Kubernetes (supports monolith and independent modules).
  • ๐ŸŒ IaC with OpenTofu: Reproducible base infrastructure (VPC, EKS, RDS) managed with OpenTofu and Terragrunt.
  • ๐Ÿค– CI/CD: GitHub Actions pipelines for automatic validation.

๐Ÿ› ๏ธ Prerequisites

  • Go 1.24+
  • Docker & Docker Compose
  • Development tools:
    • sqlc
    • buf
    • migrate
    • air
    • golangci-lint

๐Ÿš€ Quick Start

Quick Setup (Recommended)

The fastest way to get started is using the automated quickstart script:

make quickstart

This will:

  1. Validate your environment setup
  2. Install missing development tools
  3. Start Docker infrastructure
  4. Run database migrations
  5. Optionally run seed data

๐Ÿ’ก Tip: For a minimal setup (database + Redis only), use make docker-up-minimal.

Manual Setup

1. Validate Setup (Optional but Recommended)

Check that all prerequisites are installed:

make validate-setup

2. Install dependencies

make install-deps

3. Start Complete Infrastructure

The template includes a complete observability stack for local development:

make docker-up

This starts:

๐Ÿ’ก Tip: To start only the database and Redis, use make docker-up-minimal.

4. Configure (Optional)

The project supports multiple configuration sources with clear precedence:

  • PORT (standard 12-factor variable): Highest priority, compatible with Heroku, Cloud Run, Railway, etc.
  • YAML (configs/server.yaml): High priority, ideal for environment-specific configurations
  • .env: Overrides system environment variables
  • System environment variables: Base values
  • Defaults: Hardcoded values in config.go

Priority: PORT > YAML > .env > system ENV vars > defaults

Edit configs/server.yaml with your configuration values (DB connection, JWT secret, OAuth, etc.).

On startup, you'll see a log showing the source of each configuration variable.

๐Ÿ’ก OAuth Tip: To enable OAuth providers (Google, GitHub, etc.), configure credentials in configs/server.yaml or in your .env file. See complete OAuth guide.

5. Run in Development (Hot Reload)

make dev

To run a specific module with hot reload:

make dev-module auth

To run the worker process (background tasks):

make dev-worker
# or
make build-worker && ./bin/worker

๐Ÿ’ก Tip: Air automatically monitors changes in .go, .yaml, .env, .proto, .sql and configuration files, restarting the server instantly.

5. Secrets Management

The template includes an abstraction for secrets management that allows using different providers:

  • Development: Environment variables (EnvProvider implementation)
  • Production: HashiCorp Vault, AWS Secrets Manager, etc. (extensible)

See environment variables documentation for more details.

6. Stateless Processes (12-Factor App)

The template follows the stateless processes principle:

  • โœ… No local state: No temporary files are written or state stored on disk
  • โœ… State in external services: Sessions in PostgreSQL, optional cache in Redis
  • โœ… Horizontal scaling: Any instance can handle any request
  • โš ๏ธ WebSocket: Requires sticky sessions for scaling (see documentation)

See complete documentation: docs/MODULITH_ARCHITECTURE.md (section 20: Stateless Processes)

7. Health Checks and Monitoring

The server exposes health check endpoints for integration with orchestrators (Kubernetes, Docker Swarm, etc.):

  • /livez: Liveness probe - always returns 200 if the process is alive
  • /readyz: Readiness probe - checks dependencies (DB, modules, event bus, WebSocket)
  • /healthz: Legacy endpoint (backward compatibility, same as /livez)
  • /healthz/ws: WebSocket connection status (active connections and connected users)

The /readyz endpoint returns detailed JSON with the status of each dependency:

{
    "status": "ready",
    "checks": {
        "modules": "healthy",
        "database": "healthy",
        "event_bus": "healthy",
        "websocket": "healthy"
    }
}

If any dependency is unhealthy, the endpoint returns 503 Service Unavailable.

8. Administrative Tasks

The template includes an administrative task system for maintenance operations:

Available tasks:

  • cleanup-sessions: Cleans expired user sessions
  • cleanup-magic-codes: Cleans expired magic codes

Usage:

# Run an administrative task
make admin TASK=cleanup-sessions

# Or directly with the binary
./bin/server admin cleanup-sessions
./bin/server admin cleanup-magic-codes

# List available tasks
./bin/server admin

Administrative tasks run as independent commands and are useful for:

  • Periodic cleanup of expired data
  • Database maintenance
  • Data migration operations
  • Audit tasks

๐Ÿ“– Complete Documentation

๐Ÿ“‹ API Documentation

The project automatically generates OpenAPI/Swagger documentation:

  • Location: gen/openapiv2/proto/ (generated with make proto)
  • Format: JSON compatible with Swagger UI
  • Usage: Import .swagger.json files into Swagger Editor or any compatible tool

Example for the auth module:

# Generate documentation
make proto

# View the API
open gen/openapiv2/proto/auth/v1/auth.swagger.json

๐Ÿ› ๏ธ Useful Commands (Makefile)

Code Generation

  • make proto: Generates gRPC code from .proto files (includes OpenAPI/Swagger in gen/openapiv2/).
  • make sqlc: Generates Type-safe code for SQL queries.

Build

  • make build: Compiles the monolith binary in bin/server.
  • make build-module MODULE_NAME: Compiles the binary for a specific module (e.g.: make build-module auth).
  • make build-all: Compiles all binaries (server + all modules).
  • make clean: Removes all build artifacts (bin/ directory).

Setup & Validation

  • make quickstart: Automated setup process (installs deps, starts docker, runs migrations).
  • make validate-setup: Validates development environment setup (prerequisites, tools, ports).
  • make doctor: Comprehensive development environment diagnostics (containers, connectivity, configuration).

Docker

  • make docker-up: Starts all infrastructure services (PostgreSQL, Redis, Jaeger, Prometheus, Grafana).
  • make docker-up-minimal: Starts minimal services (PostgreSQL + Redis only) for faster startup.
  • make docker-down: Stops Docker containers.
  • make docker-build: Builds the server Docker image (modulith-server:latest).
  • make docker-build-module MODULE_NAME: Builds the Docker image for a specific module (e.g.: make docker-build-module auth).

Code Quality

  • make lint: Runs the strict linter (MANDATORY after changes to .go files).
  • make test: Runs all unit tests.
  • make test-unit: Runs unit tests with mocks (fast, no DB).
  • make test-coverage: Runs tests and generates HTML coverage report.
  • make coverage-report: Shows detailed coverage report in terminal.
  • make coverage-html: Opens coverage report in browser.
  • make generate-mocks: Generates interface mocks for testing.
  • make install-mocks: Installs gomock for mock generation.

Development

  • make dev: Runs the monolith server with hot reload.
  • make dev-module MODULE_NAME: Runs a specific module with hot reload (e.g.: make dev-module auth).
  • make new-module MODULE_NAME: Creates boilerplate for a new functional module with automatic configuration (generates structure + .air.{MODULE_NAME}.toml).

Database

  • make migrate-up / make migrate: Runs migrations for all modules (the modulith discovers them automatically).
  • make migrate-down MODULE=auth: Reverts the last migration for a specific module.
  • make migrate-create MODULE=auth NAME=add_users: Creates a new migration for a specific module.
  • make db-down: โš ๏ธ Deletes all database tables (destructive).
  • make db-reset: โš ๏ธ Deletes everything and runs all migrations (equivalent to db-down + migrate-up).

Note: Migrations run automatically when you start the server. The modulith discovers and applies migrations for all registered modules.

Administrative Tasks

  • make admin TASK=cleanup-sessions: Runs administrative task to clean expired sessions.
  • make admin TASK=cleanup-magic-codes: Runs administrative task to clean expired magic codes.
  • ./bin/server admin <task_name>: Runs an administrative task directly.

Note: Administrative tasks run as independent commands. You can list available tasks by running ./bin/server admin without arguments.

GraphQL (Optional)

  • make graphql-init: Adds optional GraphQL support using gqlgen and automatically generates code (one command does everything).
  • make graphql-generate-all: Generates GraphQL code from schemas for all modules.
  • make graphql-generate-module MODULE_NAME=<name>: Generates GraphQL code for a specific module (auto-generates schema from proto if missing).
  • make graphql-from-proto: Generates GraphQL schemas from OpenAPI/Swagger definitions for all modules.
  • make graphql-validate: Validates GraphQL schema.

โš ๏ธ Quality Workflow

After modifying .go files:

  1. Run make lint and fix all errors (0 issues).
  2. Run make test to verify you didn't break anything.
  3. NEVER modify .golangci.yaml to ignore errors - implement proper fixes.

Troubleshooting

If you encounter issues with your development environment:

  1. Run diagnostics: make doctor - Comprehensive health check of your environment
  2. Validate setup: make validate-setup - Check prerequisites and configuration
  3. Check containers: docker-compose ps - Verify Docker containers are running
  4. View logs: docker-compose logs [service] - Check service logs
  5. Reset database: make db-reset - Drop and recreate database (destructive)

Common issues:

  • Port conflicts: Use make doctor to identify which ports are in use
  • Docker not running: Start Docker Desktop or docker service
  • Database connection errors: Ensure containers are running with make docker-up
  • Missing tools: Run make install-deps to install all development tools

Made with โค๏ธ for developers seeking operational excellence.

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors