A production-ready Go microservice template following Clean Architecture principles with REST and gRPC support.
- ποΈ Clean Architecture - Clear separation of concerns with dependency injection
- π Dual Protocol - Both REST (HTTP) and gRPC APIs
- ποΈ MongoDB Integration - Repository pattern for data access
- π° RabbitMQ Consumer - Async message processing
- π Structured Logging - Comprehensive logging across all layers
- β Input Validation - Request validation with clear error messages
- π‘οΈ Error Handling - Centralized error handling for HTTP and gRPC
- π Middleware & Interceptors - Logging, recovery, and CORS
- π§ͺ Testable - Dependency injection enables easy unit testing
- π³ Docker Ready - Dockerfile and docker-compose included
- π Health Check -
/healthendpoint for monitoring - π― Graceful Shutdown - Proper cleanup on termination
.
βββ api/ # Presentation layer
β βββ dto/ # Data transfer objects
β βββ handlers/ # HTTP request handlers
β βββ grpc/ # gRPC service implementation
β βββ middleware/ # HTTP middleware
β βββ interceptor/ # gRPC interceptors
βββ business/ # Business logic layer
β βββ service/ # Business services
β βββ types/ # Domain models
βββ internal/ # Internal packages
β βββ config/ # Configuration management
β βββ database/ # Database connection
β βββ repository/ # Data access layer
β βββ server/ # Server initialization
βββ pkg/ # Shared packages
β βββ errors/ # Custom error types
β βββ logger/ # Logging interface
β βββ validator/ # Input validation
βββ proto/ # Protocol Buffer definitions
βββ cmd/go-api/ # Application entry point
βββ consumers/ # Message queue consumers
See ARCHITECTURE.md for detailed architecture documentation.
- Go 1.24 or higher
- MongoDB instance
- RabbitMQ instance
- Protocol Buffers compiler (protoc) - for regenerating gRPC code
- Docker (optional) - for containerized deployment
- Clone the repository
git clone <your-repo-url>
cd go-api-template- Copy environment configuration
cp env.example .env- Update
.envwith your configuration
MONGO_URI=mongodb://localhost:27017/go-api-template
RABBITMQ_URI=amqp://guest:guest@localhost:5672/
PORT=8080
GRPC_PORT=50051# Install dependencies
go mod download
# Run the application
make runThe service will start:
- HTTP API: http://localhost:8080
- gRPC API: localhost:50051
# Start all services (API + MongoDB + RabbitMQ)
make docker-compose-up
# View logs
make docker-compose-logs
# Stop all services
make docker-compose-downAccess:
- API: http://localhost:8080
- RabbitMQ Management: http://localhost:15672 (guest/guest)
curl http://localhost:8080/healthcurl http://localhost:8080/taskscurl "http://localhost:8080/tasks?id=1"curl -X POST http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":"1","title":"Learn Go","done":false}'curl -X PUT http://localhost:8080/tasks \
-H "Content-Type: application/json" \
-d '{"id":"1","title":"Learn Go","done":true}'curl -X DELETE "http://localhost:8080/tasks?id=1"The gRPC service provides the same functionality through gRPC endpoints.
List services:
grpcurl -plaintext localhost:50051 listGet all tasks:
grpcurl -plaintext localhost:50051 task.TaskService/GetTasksCreate a task:
grpcurl -plaintext -d '{"id":"1","title":"Learn gRPC","done":false}' \
localhost:50051 task.TaskService/CreateTaskUpdate a task:
grpcurl -plaintext -d '{"id":"1","title":"Learn gRPC","done":true}' \
localhost:50051 task.TaskService/UpdateTaskDelete a task:
grpcurl -plaintext -d '{"id":"1"}' \
localhost:50051 task.TaskService/DeleteTask# Run all tests
make test
# Run tests with coverage
go test -cover ./...
# Run specific package tests
go test -v ./business/service/...make run # Run the application
make build # Build binary
make test # Run tests
make proto # Generate gRPC code from .proto files
make docker-build # Build Docker image
make docker-compose-up # Start all services with Docker Compose
make docker-compose-down # Stop all servicesIf you modify proto/task.proto:
make protoThis template follows the Standard Go Project Layout and Clean Architecture:
api/: Presentation layer - handles external communicationbusiness/: Domain layer - contains business logicinternal/: Private application codepkg/: Public library code that can be importedcmd/: Main applications
- Dependency Rule: Dependencies point inward toward business logic
- Independence: Business logic doesn't depend on frameworks or external tools
- Testability: Each layer can be tested independently
- Repository Pattern: Abstract data access
- Dependency Injection: Constructor injection for all dependencies
- Interface Segregation: Small, focused interfaces
- DTO Pattern: Separate API contracts from domain models
See ARCHITECTURE.md for complete architecture documentation.
Environment variables:
| Variable | Description | Default |
|---|---|---|
MONGO_URI |
MongoDB connection string | - |
RABBITMQ_URI |
RabbitMQ connection string | - |
PORT |
HTTP server port | 8080 |
GRPC_PORT |
gRPC server port | 50051 |
RABBITMQ_EXCHANGE |
RabbitMQ exchange name | TASKS_EXCHANGE |
RABBITMQ_QUEUE |
RabbitMQ queue name | TASKS_QUEUE |
Major dependencies:
- Web Framework: Standard library
net/http - gRPC:
google.golang.org/grpc - MongoDB Driver:
go.mongodb.org/mongo-driver - RabbitMQ:
github.com/rabbitmq/amqp091-go - Validation:
github.com/go-playground/validator/v10
make docker-buildNote: The Docker image does NOT include .env files. Pass environment variables at runtime:
docker run -p 8080:8080 -p 50051:50051 \
-e MONGO_URI="mongodb://host:27017/db" \
-e RABBITMQ_URI="amqp://guest:guest@host:5672/" \
-e PORT=8080 \
-e GRPC_PORT=50051 \
go-api-template:latestOr use --env-file:
docker run -p 8080:8080 -p 50051:50051 --env-file .env go-api-template:latestFull stack with MongoDB and RabbitMQ:
docker-compose up -dNote: docker-compose.yml includes environment variables inline. For production, use secrets or external configuration.
Consistent error handling across both protocols:
HTTP Response:
{
"code": "NOT_FOUND",
"message": "Resource not found"
}gRPC Status: Appropriate gRPC status codes with descriptive messages
Structured logging throughout the application:
[INFO] 2024/01/01 12:00:00 Task created successfully: task-123
[ERROR] 2024/01/01 12:00:01 Failed to connect to database: connection refused
The /health endpoint provides service health status:
curl http://localhost:8080/health
# {"status":"ok"}This is a template repository. To use it:
- Fork or use as template
- Update module name in
go.mod - Update import paths throughout the code
- Customize for your use case
This template is provided as-is for use in your projects.
Future enhancements:
- Prometheus metrics
- Distributed tracing (OpenTelemetry)
- JWT authentication
- Rate limiting
- Redis caching
- API versioning
- OpenAPI/Swagger documentation
- Database migrations
- Circuit breaker pattern