This project provides a robust and scalable boilerplate for building Go applications with a layered architecture. It's designed to offer a clear separation of concerns, making development, testing, and maintenance more efficient.
- Layered Architecture: Clear separation of concerns (handlers, services, repositories, infrastructure).
- Configuration Management: Environment variable loading with sensible defaults using
godotenv. - Dependency Injection: Container for managing application dependencies.
- Error Handling: Custom error types for consistent error responses with proper HTTP status codes.
- JWT Authentication: JWT-based authentication with separate issuer and secret configuration.
- Request ID Middleware: Unique request tracking for correlation across logs.
- Rate Limiting: Redis-backed rate limiting to prevent abuse (100 requests/minute default).
- Security Headers: Automatic security headers (X-Content-Type-Options, X-Frame-Options, CSP, etc.).
- File Upload Validation: File size, type, and sanitization for secure uploads (10MB max, configurable file types).
- Sensitive Data Sanitization: Automatic redaction of passwords, tokens, and secrets from logs.
- Database Integration: MySQL/PostgreSQL compatible setup with GORM.
- Connection Pool Management: Configurable connection pooling (max idle, max open, connection lifetime).
- Migration Support: Built-in database migration system.
- Charset Configuration: Configurable database charset (default: utf8mb4).
- Email Service: Configurable email sending with customizable from address.
- Queue System: Redis-backed queue for asynchronous task processing.
- Cache System: Redis-backed cache for frequently accessed data.
- Storage: Local disk and S3-compatible object storage with path-style configuration.
- Logging: Structured logging with configurable levels, daily rotation, and dual output (console + file).
- API Versioning: Versioned API endpoints with
/api/v1prefix. - Data Transfer Objects (DTOs): Validated structures for API request/response payloads.
- Graceful Shutdown: Proper HTTP server shutdown handling for in-flight requests.
- CORS Support: Configurable CORS with security warnings for production.
- Event Dispatcher: In-application event system for decoupled logic.
- Async Listeners: Background event processing with queue integration.
- HTTP Request Events: Automatic request logging with sanitized payloads.
- Authentication Middleware: JWT token validation with safe type assertions.
- Request ID Middleware: Adds unique identifiers to every request.
- Rate Limiting Middleware: Prevents API abuse with Redis-backed counters.
- Security Headers Middleware: Adds essential security headers to all responses.
- CORS Middleware: Cross-origin resource sharing support.
- Constants Management: Centralized constants for magic numbers and timeouts.
- Type-Safe Operations: Proper nil checks and safe type assertions throughout.
- Structured Logging: WithFields pattern for better log analysis.
The project follows a layered architecture pattern, typically structured as follows:
cmd/: Contains the main application entry point.internal/: Houses the core application logic, divided into:config/: Application configuration loaded from environment variables.container/: Dependency injection container.customerror/: Custom error definitions.dto/: Data Transfer Objects for API requests and responses.entity/: Domain entities/models.event/: Event definitions and listeners.handler/: HTTP request handlers (controllers).helper/: Utility functions (e.g., response formatting, security).infrastructure/: External concerns like database, logger, email, queue, authenticator, validator.middleware/: HTTP middleware.queue/: Queue job definitions.repository/: Data access layer for interacting with entities.service/: Business logic layer.
- Go (version 1.20 or higher recommended)
- Docker (for local database, Redis, etc.)
-
Clone the repository:
git clone https://github.com/openframebox/goinit-layered.git cd goinit-layered -
Copy environment variables:
cp .env.example .env # Edit .env file with your specific configurations -
Install dependencies:
go mod tidy
-
Start Docker services (e.g., database, Redis): You might need a
docker-compose.ymlfile to easily spin up your dependencies. An example could look like this:# docker-compose.yml (example) version: '3.8' services: db: image: mysql:8.0 environment: MYSQL_ROOT_PASSWORD: root_password MYSQL_DATABASE: mymodule ports: - "3306:3306" redis: image: redis:latest ports: - "6379:6379"
Then run:
docker-compose up -d
-
Manage database migrations: The project uses a built-in migration tool. All migration files are located in
internal/infrastructure/database/migration/.-
Create a new migration:
go run cmd/main.go migration -a create -n create_users_table -d internal/infrastructure/database/migration
(Replace
create_users_tablewith your migration name) -
Run all pending migrations:
go run cmd/main.go migration -a migrate
-
Rollback the last migration:
go run cmd/main.go migration -a rollback -s 1
-
Clean (drop all tables):
go run cmd/main.go migration -a clean
-
List all migrations and their status:
go run cmd/main.go migration -a list
-
-
Run the HTTP Server:
go run cmd/main.go run:server
The application should start on the port specified in your
.envfile (default:8080). -
Run the Background Worker:
go run cmd/main.go run:worker
This will start the worker process for handling background tasks (e.g., queue jobs).
This boilerplate provides a solid foundation for building Go applications. It's designed to be highly adjustable to your specific needs. You can:
- Create new features: Leverage the layered architecture to add new functionalities by creating new handlers, services, and repositories.
- Manage database migrations: Easily create and run database migrations to evolve your schema.
- Send emails: Utilize the integrated email service to send various types of notifications.
- Process background tasks: Use the queue system for asynchronous processing of tasks.
- Integrate with external services: Extend the infrastructure layer to connect with other APIs or services.
- Customize configuration: Adjust environment variables in the
.envfile to suit your deployment environment.
All endpoints (except health check) are prefixed with /api/v1:
GET /health- Health check endpoint (no versioning)POST /api/v1/auth/login- User loginPOST /api/v1/auth/register- User registrationGET /api/v1/auth/profile- Get user profile (authenticated)GET /api/v1/users- List users (authenticated)POST /api/v1/example/upload- File upload example
IMPORTANT for Production:
- Generate a strong
AUTH_SECRETusing:openssl rand -base64 32 - Update
SERVER_ALLOW_ORIGINSto specific domains (remove*) - Use HTTPS and uncomment HSTS header in security middleware
- Review and adjust rate limiting based on your needs
- Implement proper password complexity requirements
- Use a secrets management system for sensitive configuration
The boilerplate includes extensive configuration options via environment variables:
Database:
- Connection pool settings (max idle/open connections, connection lifetime)
- Charset configuration
- Debug query logging
Email:
- Configurable from address (name and email)
- SMTP settings with SSL/TLS support
Security:
- Separate auth issuer and secret
- Rate limiting (requests per minute)
- CORS origins
Logging:
- Configurable log level (debug, info, warn, error)
- Daily log rotation
- Dual output (console + JSON file)
See .env.example for all available configuration options.
Contributions are welcome! Please feel free to open issues or submit pull requests.
This project is licensed under the MIT License. See the LICENSE file for details.