A production-ready microservice template built with Golang and Gin framework, converted from a FastAPI template. This template implements clean architecture principles, comprehensive security features, and modern Go best practices.
- Clean Architecture: Separation of concerns with clear layers (handlers β services β repositories β models)
- RESTful API: Built with Gin framework for high performance
- PostgreSQL Database: GORM ORM with connection pooling and migrations
- Redis Caching: Distributed caching with connection pooling
- JWT Authentication: Secure authentication with device tracking and multi-device support
- Structured Logging: Zap logger with context propagation and log rotation
- Rate Limiting: Configurable per-minute and per-hour limits
- Attack Detection: SQL injection, XSS, and path traversal detection
- IP Filtering: IP whitelist/blacklist with automatic blocking
- User Agent Filtering: Bot and suspicious client detection
- Password Hashing: Bcrypt with configurable cost
- Device Fingerprinting: Unique device identification and tracking
- Environment-based Configuration: Viper for flexible config management
- Dependency Injection: Constructor-based DI for testability
- Generic Base Repository: Type-safe CRUD operations with Go generics
- Comprehensive Error Handling: Custom error types with HTTP status codes
- Docker Support: Multi-stage builds and docker-compose setup
- Makefile: Common development tasks automated
golang-microservice-template/
βββ cmd/
β βββ server/
β βββ main.go # Application entry point
βββ internal/ # Private application code
β βββ api/
β β βββ handlers/ # HTTP handlers (controllers)
β β βββ middleware/ # HTTP middleware
β β βββ routes/ # Route definitions
β β βββ dto/ # Data Transfer Objects
β βββ domain/ # Business logic layer
β β βββ models/ # Domain models (DB entities)
β β βββ repository/ # Repository interfaces
β β βββ services/ # Business logic services
β βββ infrastructure/ # External dependencies
β β βββ database/ # PostgreSQL connection
β β βββ cache/ # Redis client
β β βββ persistence/ # Repository implementations
β βββ pkg/ # Internal utilities
β β βββ config/ # Configuration management
β β βββ logger/ # Logging setup
β β βββ security/ # Security utilities
β β βββ errors/ # Custom error types
β β βββ validator/ # Custom validators
β βββ app/
β βββ app.go # Application initialization
βββ pkg/ # Public packages (reusable)
βββ configs/ # Configuration files
βββ migrations/ # Database migrations
βββ docker/ # Docker files
βββ scripts/ # Build/deployment scripts
βββ go.mod
βββ go.sum
βββ Makefile
βββ README.md
βββββββββββββββββββββββββββββββββββββββββββ
β API Layer (Handlers) β
β - HTTP request/response handling β
β - Input validation β
β - Response formatting β
βββββββββββββββββββ¬ββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββ
β Service Layer (Business Logic) β
β - Business rules β
β - Orchestration β
β - Transaction management β
βββββββββββββββββββ¬ββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββ
β Repository Layer (Data Access) β
β - Database operations β
β - Query building β
β - Data mapping β
βββββββββββββββββββ¬ββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββ
β Domain Layer (Models) β
β - Entity definitions β
β - Business entities β
β - Domain logic β
βββββββββββββββββββββββββββββββββββββββββββ
- Handlers depend on Services
- Services depend on Repository Interfaces
- Repository Implementations depend on Models
- Models have no dependencies (pure domain)
| Component | Technology |
|---|---|
| Web Framework | Gin |
| ORM | GORM |
| Database | PostgreSQL |
| Cache | Redis |
| Configuration | Viper |
| Logging | Zap |
| JWT | golang-jwt |
| Validation | validator |
| Password Hashing | bcrypt |
- Go 1.21 or higher
- PostgreSQL 14+
- Redis 6+
- Docker & Docker Compose (optional)
-
Clone the repository
git clone <repository-url> cd golang-microservice-template
-
Install dependencies
go mod download
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Run database migrations
make migrate-up
-
Run the application
make run
The server will start on http://localhost:8000
# Build and run all services
docker-compose up -d
# View logs
docker-compose logs -f
# Stop services
docker-compose downThis project uses Swagger/OpenAPI for API documentation. Once the server is running, you can access the interactive API documentation at:
- Swagger UI:
http://localhost:8000/api/swagger/index.html - API JSON:
http://localhost:8000/api/swagger/doc.json
- Interactive API Testing: Try out endpoints directly from the browser
- Request/Response Examples: See sample data for all endpoints
- Authentication: Test protected endpoints with JWT tokens
- Schema Validation: View detailed request/response schemas
To regenerate the Swagger documentation after making changes:
# Install swag CLI (if not already installed)
go install github.com/swaggo/swag/cmd/swag@latest
# Generate documentation
swag init -g cmd/server/main.go -o docsConfiguration is managed through environment variables and YAML files. The application supports multiple environments (development, staging, production).
Key environment variables:
# Server
SERVER_HOST=0.0.0.0
SERVER_PORT=8000
# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=microservice_db
DB_USER=postgres
DB_PASSWORD=postgres
# JWT
JWT_SECRET_KEY=your-secret-key
JWT_ACCESS_TOKEN_EXPIRATION_MINUTES=60
JWT_REFRESH_TOKEN_EXPIRATION_DAYS=30
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379See .env.example for all available options.
- JWT-based authentication with access and refresh tokens
- Device tracking with unique device fingerprinting
- Multi-device support with configurable limits
- Token blacklisting for logout functionality
- Role-based access control (RBAC)
- Rate Limiter: Prevents abuse with configurable limits
- Attack Detector: Detects SQL injection, XSS, path traversal
- IP Filter: Whitelist/blacklist with automatic blocking
- User Agent Filter: Blocks suspicious bots and clients
- Bcrypt hashing with configurable cost (default: 12)
- Password strength validation
- Salt generation for additional security
POST /api/auth/register # Register new user
POST /api/auth/login # Login user
POST /api/auth/refresh-token # Refresh access token
POST /api/auth/logout # Logout current device
POST /api/auth/logout-all # Logout all devices
GET /api/auth/devices # Get user devices
GET /api/auth/devices/:id # Get device details
GET /api/users # Get all users (admin)
GET /api/users/:id # Get user by ID
PUT /api/users/:id # Update user
DELETE /api/users/:id # Delete user
GET /api/health # Health check
GET /api/health/db # Database health
GET /api/health/redis # Redis health
# Run all tests
make test
# Run tests with coverage
make test-coverage
# Run specific package tests
go test ./internal/pkg/security/...make build # Build the application
make run # Run the application
make test # Run tests
make test-coverage # Run tests with coverage
make lint # Run linter
make fmt # Format code
make clean # Clean build artifacts
make docker-build # Build Docker image
make docker-run # Run in Docker
make migrate-up # Run database migrations
make migrate-down # Rollback migrationsThe included Dockerfile uses multi-stage builds for optimal image size:
- Builder stage: Compiles the Go application
- Final stage: Minimal runtime image with just the binary
Includes services for:
- Application server
- PostgreSQL database
- Redis cache
- Database admin (Adminer)
- Connection pooling for database and Redis
- Prepared statements for database queries
- Goroutines for async operations (background tasks)
- Context propagation for request cancellation
- Efficient JSON serialization with Gin
- Log rotation to prevent disk space issues
(Add your benchmark results here)
This template is a direct conversion from a FastAPI microservice. Key mappings:
| FastAPI | Golang/Gin |
|---|---|
| Pydantic models | Structs with validation tags |
| Dependency injection | Constructor injection |
| async/await | Goroutines + channels |
| SQLAlchemy async | GORM with context |
| Alembic migrations | golang-migrate or GORM AutoMigrate |
| FastAPI middleware | Gin middleware |
| Loguru | Zap |
| Python decorators | Function wrappers |
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Converted from FastAPI microservice template
- Inspired by clean architecture principles
- Built with modern Go best practices
For issues and questions:
- Open an issue on GitHub
- Contact: your-email@example.com
Built with β€οΈ using Golang and Gin