A flexible Go application template framework that supports multiple service types and optional component integration, suitable for quickly building various backend services.
- Multi-protocol support: HTTP, TCP, UDP services
- Custom binary protocol: TCP/UDP with JSON and Gob encoding support
- Modular design: Enable only what you need
- Dependency injection: Manual constructor injection in
internal/app - Configuration management: YAML/JSON with environment variable override for sensitive data only
- Structured logging: Zap with log rotation
- Graceful shutdown: Signal handling and resource cleanup
- Health checks: /health, /readiness, /liveness endpoints
- CLI tools: Built with Cobra
- Database integration: Bun ORM with support for MySQL, PostgreSQL, SQLite
- Database migrations: Built-in migration tool for schema management
- Code generation: Model generation from database tables
- Observability: Configurable distributed tracing (OpenTelemetry) and metrics (Prometheus)
- Optional packages:
pkg/payment,pkg/objectstorage,pkg/captcha,pkg/lock,pkg/eventare reusable building blocks — the sample app demonstrates basic HTTP/CRUD flow and does not wire every package
- Go 1.27.3 or higher
# Clone the repository
git clone https://github.com/ilaziness/app-tpl.git
cd app-tpl
# Download dependencies
make deps# Run with default configuration
make run
# Run with development configuration
make run-dev
# Or build and run
make build
./build/app-tpl serve# Start the server with default config
./build/app-tpl serve
# Start with environment overlay (merges config.{env}.yaml onto config.yaml)
./build/app-tpl serve -e dev
./build/app-tpl serve -e prod
./build/app-tpl serve -e test
# Optional: explicit primary file (default is configs/config.yaml)
./build/app-tpl serve -c configs/config.yaml -e prod
# Show version
./build/app-tpl version
# Validate / show effective config
./build/app-tpl config validate -e prod
./build/app-tpl config show -e prod
./build/app-tpl config show --check -e prod
# Database migrations
./build/app-tpl migrate up # Run all pending migrations
./build/app-tpl migrate down # Rollback last migration
./build/app-tpl migrate status # Show migration status
./build/app-tpl migrate create <name> # Create new migration files
./build/app-tpl migrate up --dry-run # Preview migrations without executing
# Code generation
./build/app-tpl gen model # Generate models for the configured DB driver
./build/app-tpl gen model --table users,orders --output ./internal/model
./build/app-tpl gen model --dry-run --with-relations
# Show help
./build/app-tpl --helpConfiguration can be provided via:
- YAML files:
configs/config.yaml(full catalog), sparse overlaysconfig.{dev,prod,test}.yaml - Command-line:
--env / -eselects an overlay;--config / -csets the primary file (defaultconfigs/config.yaml) - Environment variables: Only for secrets (passwords, API keys) — see
configs/.env.example
--env/APP_ENV(selects overlay; locksapp.envwhen set)- Process env vars for sensitive fields only
- Optional dotenv files (fill unset secrets)
config.{env}.yamloverlay — only when--envorAPP_ENVis set and the primary file is namedconfig.yaml- Primary YAML (
-corconfigs/config.yaml) - Built-in code defaults
Bare serve (no APP_ENV) loads only the base catalog (SQLite-ready). Production: set APP_ENV=prod (or -e prod) and inject secrets; do not bake APP_ENV into the image.
config.yaml— full catalog with comments for every keyconfig.dev.yaml/config.prod.yaml/config.test.yaml— sparse env overlays (no secrets, noapp.env)- Escape hatch:
-c path/to/complete.yaml(not namedconfig.yaml) loads that file alone
export DATABASE_PASSWORD=
export REDIS_PASSWORD=
export JWT_SECRET= # required in production (≥32 bytes)
export HTTP_INTERNAL_SERVICE_KEY=
export OBJECT_STORAGE_ACCESS_KEY=
export OBJECT_STORAGE_SECRET_KEY=See configs/.env.example. CLI helpers: config validate, config show [--check].
This template includes database integration using Bun ORM with support for MySQL, PostgreSQL, and SQLite.
- SQLite: Default for development and testing
- MySQL: For production environments
- PostgreSQL: For production environments
Configure the database in your config files:
database:
enabled: true
driver: sqlite
host: ""
port: 0
database: ./data/app.db
user: ""
password: ""
ssl_mode: disable
max_open_conns: 25
max_idle_conns: 5
conn_max_lifetime: 5m# Create a new migration
./build/app-tpl migrate create add_users_table
# Run migrations
./build/app-tpl migrate up
# Check migration status
./build/app-tpl migrate status
# Rollback last migration
./build/app-tpl migrate down# Generate models from all tables
./build/app-tpl gen model
# Generate model for specific table
./build/app-tpl gen model --table users
# Customize output
./build/app-tpl gen model --table users --output ./internal/model --package model.
├── cmd/ # Command line interface
│ ├── root.go # Root command
│ ├── serve.go # Serve command
│ ├── config.go # Config management commands
│ ├── version.go # Version command
│ ├── migrate.go # Database migration commands
│ └── gen.go # Code generation commands
├── configs/ # Configuration files
├── migrations/ # Database migration files
│ ├── *.up.sql # Up migration files
│ └── *.down.sql # Down migration files
├── internal/ # Private application code
│ ├── app/ # Application wiring and lifecycle
│ ├── config/ # Configuration structures
│ ├── constant/ # Application constants
│ ├── database/ # Database initialization
│ ├── errors/ # Error types and codes
│ ├── handler/ # Request handlers
│ │ ├── http/ # HTTP handlers
│ │ │ ├── user.go # User handler
│ │ │ └── health.go # Health check handler
│ │ ├── tcp/ # TCP handlers
│ │ │ ├── handler.go # Handler interface
│ │ │ ├── echo.go # Echo service
│ │ │ └── chat.go # Chat room service
│ │ └── udp/ # UDP handlers
│ │ ├── handler.go # Handler interface
│ │ ├── time.go # Time query service
│ │ └── stats.go # Statistics service
│ ├── logger/ # Logging wrapper
│ ├── middleware/ # Middlewares
│ │ ├── http/ # HTTP-specific middlewares
│ │ ├── tcp/ # TCP middlewares
│ │ │ ├── auth.go # Authentication
│ │ │ ├── ratelimit.go # Rate limiting
│ │ │ ├── logger.go # Logging
│ │ │ └── timeout.go # Timeout control
│ │ └── udp/ # UDP middlewares
│ │ ├── auth.go # Authentication
│ │ ├── ratelimit.go # Rate limiting
│ │ └── logger.go # Logging
│ ├── protocol/ # Protocol codecs
│ │ ├── codec.go # Codec interfaces
│ │ ├── custom_protocol.go # Custom binary protocol
│ │ ├── json_codec.go # JSON codec
│ │ └── binary_codec.go # Binary (Gob) codec
│ ├── response/ # API response structures
│ ├── router/ # Route registration
│ ├── server/ # Server implementations
│ │ ├── http.go # HTTP server
│ │ ├── tcp.go # TCP server
│ │ └── udp.go # UDP server
│ ├── service/ # Business logic layer
│ │ └── user.go # User service
│ ├── repository/ # Data access layer
│ │ └── user.go # User repository
│ ├── model/ # Data models
│ │ └── user.go # User model
│ └── dto/ # Data transfer objects
│ └── user.go # User DTOs
├── main.go # Application entry point
├── Makefile # Build commands
└── README.md # This file
Error codes follow the format {3-digit module code}{4-digit business code}:
100xxxx- General module (parameter errors, data not found, etc.)200xxxx- User module (user not found, user exists, etc.)300xxxx- Auth module (auth failed, token expired, permissions, etc.)900xxxx- System module (internal error, database error, cache error, etc.)
Examples:
1000001- Parameter error1000002- Data not found2000001- User not found3000001- Authentication failed3000003- Insufficient permission9000001- Internal server error
Each error code includes an associated HTTP status code.
make build # Build the application
make run # Run the application
make run-dev # Run with development config
make test # Run tests
make test-coverage # Run tests with coverage
make clean # Clean build artifacts
make deps # Download dependencies
make lint # Run linter
make fmt # Format code
make vet # Run go vetOnce the server is running, you can access:
GET /health- Basic health checkGET /readiness- Readiness check (includes dependency checks)GET /liveness- Liveness checkGET /version- Application versionGET /version- Application versionGET /metrics- Prometheus metrics (requiresmetrics.enabled: true)
Example:
curl http://localhost:8080/healthThe application supports optional TCP and UDP services with custom binary protocol support. See TCP/UDP Guide for detailed documentation.
Enable TCP/UDP services in configs/config.yaml:
tcp:
enabled: true
host: 0.0.0.0
port: 9000
codec: json
udp:
enabled: true
host: 0.0.0.0
port: 9001
codec: jsonAvailable example services:
- TCP: Echo service, Chat room
- UDP: Time query, Statistics
For more details, see TCP/UDP Guide.
The application supports configurable distributed tracing and metrics monitoring. See Observability Guide for detailed documentation.
- Distributed Tracing: OpenTelemetry with OTLP protocol (supports Jaeger, Tempo, etc.)
- Metrics Monitoring: Prometheus native client with HTTP, database, Redis, TCP, UDP metrics
- Data Correlation: trace_id automatically injected into logs and HTTP response headers
Enable observability in configs/config.yaml:
# Enable distributed tracing
tracing:
enabled: true
endpoint: localhost:4317 # OTLP gRPC endpoint
sample_rate: 1.0
# Enable metrics monitoring
metrics:
enabled: true
path: /metrics
labels:
env: dev
version: "1.0.0"Access metrics endpoint: http://localhost:8080/metrics
For detailed configuration and usage, see Observability Guide.
The application integrates Swagger API documentation. Access the following URLs to view:
- Swagger UI: http://localhost:8080/swagger/index.html
# Generate Swagger documentation
make swagger
# Clean generated documentation
make swagger-cleanThe project includes multiple example code snippets demonstrating how to use various components:
- HTTP Service: Endpoints like
/api/v1/users/{id}are complete HTTP service examples - TCP Service: EchoHandler (echo service) and ChatHandler (chat room service) are complete TCP service examples
- UDP Service: TimeHandler (time query service) is a complete UDP service example
internal/event/example_test.go- Event system usage examplesinternal/cache/example_test.go- Cache usage examples
- Module Usage Guide - How to select and remove unnecessary service modules
- Deployment Documentation - Single instance, multi-instance, and Docker deployment guides
- Observability Guide - Distributed tracing and metrics monitoring configuration
MIT License