Skip to content

About

A production-ready Go microservice template following Clean Architecture principles with REST and gRPC support. It's running right now on GCP Cloud Run.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

19 Commits

Folders and files

Repository files navigation

Go API Template

A production-ready Go microservice template following Clean Architecture principles with REST and gRPC support.

✨ Features

  • πŸ—οΈ 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 - /health endpoint for monitoring
  • 🎯 Graceful Shutdown - Proper cleanup on termination

πŸ“ Project Structure

.
β”œβ”€β”€ 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.

πŸš€ Quick Start

Prerequisites

  • Go 1.24 or higher
  • MongoDB instance
  • RabbitMQ instance
  • Protocol Buffers compiler (protoc) - for regenerating gRPC code
  • Docker (optional) - for containerized deployment

Installation

  1. Clone the repository
git clone <your-repo-url>
cd go-api-template
  1. Copy environment configuration
cp env.example .env
  1. Update .env with your configuration
MONGO_URI=mongodb://localhost:27017/go-api-template
RABBITMQ_URI=amqp://guest:guest@localhost:5672/
PORT=8080
GRPC_PORT=50051

Running Locally

# Install dependencies
go mod download

# Run the application
make run

The service will start:

Running with Docker Compose (Recommended)

# Start all services (API + MongoDB + RabbitMQ)
make docker-compose-up

# View logs
make docker-compose-logs

# Stop all services
make docker-compose-down

Access:

πŸ“š API Documentation

REST API

Health Check

curl http://localhost:8080/health

Get All Tasks

curl http://localhost:8080/tasks

Get Task by ID

curl "http://localhost:8080/tasks?id=1"

Create Task

curl -X POST http://localhost:8080/tasks \
  -H "Content-Type: application/json" \
  -d '{"id":"1","title":"Learn Go","done":false}'

Update Task

curl -X PUT http://localhost:8080/tasks \
  -H "Content-Type: application/json" \
  -d '{"id":"1","title":"Learn Go","done":true}'

Delete Task

curl -X DELETE "http://localhost:8080/tasks?id=1"

gRPC API

The gRPC service provides the same functionality through gRPC endpoints.

Using grpcurl

List services:

grpcurl -plaintext localhost:50051 list

Get all tasks:

grpcurl -plaintext localhost:50051 task.TaskService/GetTasks

Create a task:

grpcurl -plaintext -d '{"id":"1","title":"Learn gRPC","done":false}' \
  localhost:50051 task.TaskService/CreateTask

Update a task:

grpcurl -plaintext -d '{"id":"1","title":"Learn gRPC","done":true}' \
  localhost:50051 task.TaskService/UpdateTask

Delete a task:

grpcurl -plaintext -d '{"id":"1"}' \
  localhost:50051 task.TaskService/DeleteTask

πŸ§ͺ Testing

# Run all tests
make test

# Run tests with coverage
go test -cover ./...

# Run specific package tests
go test -v ./business/service/...

πŸ› οΈ Development

Makefile Commands

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 services

Regenerating Protocol Buffers

If you modify proto/task.proto:

make proto

Project Layout Philosophy

This template follows the Standard Go Project Layout and Clean Architecture:

  • api/: Presentation layer - handles external communication
  • business/: Domain layer - contains business logic
  • internal/: Private application code
  • pkg/: Public library code that can be imported
  • cmd/: Main applications

πŸ—οΈ Architecture Principles

Clean Architecture

  • 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

Key Patterns

  • 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.

πŸ”§ Configuration

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

πŸ“¦ Dependencies

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

🐳 Docker

Build Image

make docker-build

Run Container

Note: 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:latest

Or use --env-file:

docker run -p 8080:8080 -p 50051:50051 --env-file .env go-api-template:latest

Docker Compose

Full stack with MongoDB and RabbitMQ:

docker-compose up -d

Note: docker-compose.yml includes environment variables inline. For production, use secrets or external configuration.

πŸ“ Error Handling

Consistent error handling across both protocols:

HTTP Response:

{
  "code": "NOT_FOUND",
  "message": "Resource not found"
}

gRPC Status: Appropriate gRPC status codes with descriptive messages

πŸ” Logging

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

🚦 Health Check

The /health endpoint provides service health status:

curl http://localhost:8080/health
# {"status":"ok"}

🀝 Contributing

This is a template repository. To use it:

  1. Fork or use as template
  2. Update module name in go.mod
  3. Update import paths throughout the code
  4. Customize for your use case

πŸ“„ License

This template is provided as-is for use in your projects.

🎯 Roadmap

Future enhancements:

  • Prometheus metrics
  • Distributed tracing (OpenTelemetry)
  • JWT authentication
  • Rate limiting
  • Redis caching
  • API versioning
  • OpenAPI/Swagger documentation
  • Database migrations
  • Circuit breaker pattern

πŸ“š Additional Resources

About

A production-ready Go microservice template following Clean Architecture principles with REST and gRPC support. It's running right now on GCP Cloud Run.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages