Files
go-grpc-gateway-template/README.md
2025-08-13 19:36:09 +02:00

6.4 KiB

Go gRPC Gateway Template

A production-ready Go template for gRPC services with HTTP/JSON gateway support, featuring modern tooling, Docker support, and CI/CD integration.

🚀 Features

  • Dual Protocol Support - Serve both gRPC and REST APIs simultaneously
  • Modern Toolchain - Uses buf for Protocol Buffers management
  • Docker Ready - Complete containerization with multi-stage builds
  • Testing - Unit and integration tests with coverage
  • CI/CD - GitHub Actions workflows for testing and deployment
  • Health Checks - Built-in health monitoring endpoints
  • OpenAPI - Auto-generated Swagger documentation
  • Configuration - Environment-based config management
  • Observability - Structured logging and metrics ready

📁 Project Structure

├── cmd/server/              # Main application entry point
├── proto/helloworld/        # Protocol buffer definitions
├── internal/
│   ├── config/             # Configuration management
│   ├── health/             # Health check handlers
│   └── server/             # Server setup and middleware
├── pkg/                    # Shared packages (if needed)
├── tests/                  # Integration tests
├── docker/                 # Docker configuration
├── .github/workflows/      # CI/CD pipelines
├── buf.yaml               # Buf configuration
├── buf.gen.yaml           # Code generation config
├── docker-compose.yml     # Local development
└── justfile              # Task runner

🛠 Prerequisites

  • Go 1.23+
  • Docker & Docker Compose (for containerized development)
  • just task runner
  • buf (installed automatically via just install-deps)

🚦 Quick Start

1. Install Dependencies

just install-deps

2. Start Development Environment

# Start with Docker (recommended)
just dev-docker

# Or start locally
just dev

3. Test the API

# gRPC endpoint
grpcurl -plaintext -d '{"name": "World"}' localhost:8080 helloworld.Greeter/SayHello

# HTTP endpoint  
curl -X POST http://localhost:8090/v1/example/echo -d '{"name": "World"}' -H "Content-Type: application/json"

📋 Available Commands

Development

  • just install-deps - Install required tools (buf, protoc plugins)
  • just dev - Start development server locally
  • just dev-docker - Start with Docker Compose
  • just proto - Generate protobuf files
  • just build - Build the server binary

Testing & Quality

  • just test - Run unit tests
  • just test-integration - Run integration tests
  • just test-coverage - Run tests with coverage report
  • just lint - Run linter and format check
  • just format - Format code

Docker & Deployment

  • just docker-build - Build Docker image
  • just docker-run - Run container locally
  • just docker-push - Push to registry

Utilities

  • just clean - Clean build artifacts
  • just docs - Generate and serve API documentation
  • just health - Check service health

🌐 API Documentation

Endpoints

Method Path Description
POST /v1/example/echo Echo the input name
GET /health Health check endpoint
GET /metrics Prometheus metrics (if enabled)
GET /docs OpenAPI documentation

Example Requests

Echo Request:

curl -X POST http://localhost:8090/v1/example/echo \
  -H "Content-Type: application/json" \
  -d '{"name": "World"}'

Response:

{
  "message": "Hello World"
}

Health Check:

curl http://localhost:8090/health

Response:

{
  "status": "ok",
  "timestamp": "2025-08-13T19:30:00Z",
  "version": "1.0.0"
}

🐳 Docker Usage

Development with Docker Compose

# Start all services
just dev-docker

# View logs
docker-compose logs -f

# Stop services
docker-compose down

Production Docker Build

# Build optimized image
just docker-build

# Run container
just docker-run

🧪 Testing

# Run all tests
just test

# Run with coverage
just test-coverage

# Run integration tests
just test-integration

# Run specific test
go test -v ./internal/server -run TestServerHealth

🔧 Configuration

The service can be configured via environment variables:

Variable Default Description
SERVER_GRPC_PORT 8080 gRPC server port
SERVER_HTTP_PORT 8090 HTTP gateway port
LOG_LEVEL info Logging level (debug, info, warn, error)
LOG_FORMAT json Log format (json, text)
METRICS_ENABLED true Enable Prometheus metrics

Example .env file:

SERVER_GRPC_PORT=9090
SERVER_HTTP_PORT=8080
LOG_LEVEL=debug
LOG_FORMAT=text

🔄 Adding New Services

  1. Define the service in protobuf:
service UserService {
  rpc CreateUser(CreateUserRequest) returns (CreateUserResponse) {
    option (google.api.http) = {
      post: "/v1/users"
      body: "*"
    };
  }
}
  1. Generate code:
just proto
  1. Implement the service:
type UserService struct {
    helloworldpb.UnimplementedUserServiceServer
}

func (s *UserService) CreateUser(ctx context.Context, req *helloworldpb.CreateUserRequest) (*helloworldpb.CreateUserResponse, error) {
    // Implementation here
    return &helloworldpb.CreateUserResponse{}, nil
}
  1. Register in server:
helloworldpb.RegisterUserServiceServer(s, &UserService{})
helloworldpb.RegisterUserServiceHandler(ctx, gwmux, conn)

🚀 Deployment

GitHub Actions

The template includes automated workflows:

  • CI: Runs tests, linting, and security scans on PRs
  • CD: Builds and pushes Docker images on releases
  • Dependency Updates: Automated dependency updates

Manual Deployment

# Build for production
just build

# Create Docker image
just docker-build

# Deploy to your platform
just docker-push

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests: just test
  5. Submit a pull request