Skip to content

devrob-go/go-starter-grpc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Starter gRPC + REST

A production-ready Go service template that supports both gRPC and REST APIs using the same protobuf definitions, built with clean architecture principles and comprehensive test coverage.

Features

  • Dual API Support: gRPC and REST APIs from the same protobuf definitions
  • Clean Architecture: Domain, Service, Transport, and Infrastructure layers
  • High Scalability: Structured logging, context handling, graceful shutdown
  • Production Ready: Interceptors, middleware, request validation
  • Development Friendly: Hot reload, Docker Compose, comprehensive tooling
  • Comprehensive Testing: Extensive unit tests with >80% coverage target

Current Status

Test Coverage (Latest)

  • Overall Coverage: 0.9% (increasing daily)
  • Server Layer: 3.6% - Auth server, health server, middleware, interceptors
  • Storage Layer: 0.6% - Core storage, users, validations
  • Utils: 3.2% - Hashing, tokens, helpers, error handling
  • Config: 3.4% - Configuration loading and validation
  • Services: 0.2% - Auth service, user service
  • Models: 0.0% - Basic struct validation

Recently Added Tests

  • Server Layer: Complete test suite for auth server, health server, middleware
  • Storage Layer: Core storage utilities, user operations, validations
  • Utils: Hashing, JWT tokens, helper functions, custom error handling
  • Config: Environment variable parsing, configuration validation
  • Services: Service composition and basic functionality
  • Models: Data structure validation and edge cases

Architecture

┌─────────────────────────────────────────────────────────────┐
│                    Transport Layer                          │
├─────────────────────────────────────────────────────────────┤
│  gRPC Server (Port 8080)  │  REST Gateway (Port 8081)     │
│  ┌─────────────────────┐  │  ┌─────────────────────────┐  │
│  │   Auth Server       │  │  │     REST Gateway        │  │
│  │   Health Server     │  │  │     (HTTP/JSON)         │  │
│  │   Middleware        │  │  │                         │  │
│  │   Interceptors      │  │  │                         │  │
│  └─────────────────────┘  │  └─────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    Service Layer                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │ AuthService │  │UserService  │  │HealthService│        │
│  │ • SignUp    │  │ • GetUsers  │  │ • Check     │        │
│  │ • SignIn    │  │ • Pagination│  │ • Watch     │        │
│  │ • SignOut   │  │ • Validation│  │ • DB Health │        │
│  │ • Refresh   │  └─────────────┘  └─────────────┘        │
│  │ • Revoke    │                                          │
│  └─────────────┘                                          │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    Domain Layer                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │    User     │  │   Auth      │  │ Validation  │        │
│  │ • Models    │  │ • Tokens    │  │ • Rules     │        │
│  │ • Credentials│  │ • JWT      │  │ • Errors    │        │
│  │ • Validation│  │ • Security  │  │ • Messages  │        │
│  └─────────────┘  └─────────────┘  └─────────────┘        │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                Infrastructure Layer                         │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │ PostgreSQL  │  │   Redis     │  │   Logger    │        │
│  │ • Migrations│  │ • Caching   │  │ • Structured│        │
│  │ • Connection│  │ • Sessions  │  │ • Correlation│       │
│  │ • Pool      │  │ • Rate Limit│  │ • Levels    │        │
│  └─────────────┘  └─────────────┘  └─────────────┘        │
└─────────────────────────────────────────────────────────────┘

Quick Start

Prerequisites

  • Go 1.24+
  • Docker & Docker Compose
  • Protocol Buffers compiler

Installation

  1. Clone the repository

    git clone <repository-url>
    cd go-starter-grpc
  2. Install protobuf tools

    cd auth-service
    make install-tools
  3. Generate protobuf code

    make proto
  4. Start services with Docker Compose

    docker-compose up -d

Development

  • Run with hot reload: make dev
  • Build: make build
  • Run: make run
  • Test: make test
  • Clean: make clean

Testing

Test Commands

Run all tests:

go test ./...

Run tests with coverage:

go test -coverpkg=./... -coverprofile=coverage.out ./...
go tool cover -func=coverage.out

Run specific package tests:

go test -v ./server/...      # Server layer tests
go test -v ./storage/...     # Storage layer tests
go test -v ./utils/...       # Utility function tests
go test -v ./config/...      # Configuration tests
go test -v ./services/...    # Service layer tests

View coverage in browser:

go tool cover -html=coverage.out

Test Structure

  • Unit Tests: Comprehensive coverage of individual functions
  • Integration Tests: Service layer and storage interactions
  • Benchmark Tests: Performance testing for critical paths
  • Edge Case Testing: Boundary conditions and error scenarios
  • Mock Testing: Isolated testing with mocked dependencies

API Endpoints

gRPC (Port 8080)

  • AuthService: Authentication and user management
    • SignUp - User registration with validation
    • SignIn - User authentication with JWT tokens
    • SignOut - User logout and token invalidation
    • RefreshToken - Token refresh mechanism
    • RevokeToken - Token revocation
    • ListUsers - User listing with pagination
  • HealthService: Service health checks
    • Check - Single health check
    • Watch - Streaming health monitoring

REST (Port 8081)

  • POST /v1/auth/signup - User registration
  • POST /v1/auth/signin - User login
  • POST /v1/auth/signout - User logout
  • POST /v1/auth/refresh - Token refresh
  • POST /v1/auth/revoke - Token revocation
  • GET /v1/users - List users with pagination
  • GET /v1/health - Health check endpoint

Configuration

Environment variables:

  • APP_PORT: gRPC server port (default: 8080)
  • REST_PORT: REST gateway port (default: 8081)
  • POSTGRES_HOST: PostgreSQL host (default: localhost)
  • POSTGRES_PORT: PostgreSQL port (default: 5432)
  • LOG_LEVEL: Logging level (default: debug)
  • JWT_ACCESS_TOKEN_SECRET: JWT signing secret
  • JWT_REFRESH_TOKEN_SECRET: JWT refresh secret
  • HEALTH_CHECK_TIMEOUT: Health check timeout in seconds

Project Structure

auth-service/
├── cmd/                    # Application entry points
├── internal/               # Private application code
│   ├── domain/            # Domain entities and interfaces
│   ├── service/           # Business logic implementation
│   ├── transport/         # gRPC and REST handlers
│   └── infrastructure/    # Database, external services
├── proto/                 # Protocol buffer definitions
├── config/                # Configuration management
│   ├── config.go         # Main configuration struct
│   └── validation.go     # Configuration validation
├── server/                # Server setup and middleware
│   ├── auth_server.go    # Authentication gRPC server
│   ├── health_server.go  # Health check server
│   ├── middleware.go     # gRPC middleware (metrics, recovery, rate limiting)
│   ├── interceptors.go   # Logging and correlation interceptors
│   ├── register.go       # Service registration
│   └── server.go         # Main server orchestration
├── services/              # Business logic services
│   ├── auth/             # Authentication service
│   │   ├── service.go    # Service interface
│   │   ├── signin.go     # Sign-in logic
│   │   ├── signup.go     # Sign-up logic
│   │   ├── token.go      # Token management
│   │   └── refresh.go    # Token refresh
│   └── users/            # User management service
├── storage/               # Data persistence layer
│   ├── storage.go        # Core database operations
│   ├── users.go          # User CRUD operations
│   ├── user_tokens.go    # Token storage and management
│   └── validations.go    # Data validation rules
├── utils/                 # Utility functions
│   ├── hash.go           # Password hashing (bcrypt)
│   ├── token.go          # JWT token utilities
│   ├── helpers.go        # Validation helpers
│   └── errors.go         # Custom error types
├── models/                # Data models
│   ├── user.go           # User entity
│   └── user_token.go     # Token entity
├── scripts/               # Database scripts
├── Dockerfile.dev         # Development container
├── .air.toml             # Hot reload configuration
└── Makefile              # Build and development commands

Development Workflow

  1. Define APIs: Update .proto files with HTTP annotations
  2. Generate Code: Run make proto to generate Go code
  3. Implement Logic: Add business logic in service layer
  4. Add Tests: Create comprehensive unit tests for new functionality
  5. Test: Run make test to verify functionality and coverage
  6. Run: Use make dev for development with hot reload

Testing Strategy

Current Focus Areas

  • Server Layer: Complete coverage of gRPC servers and middleware
  • Storage Layer: Database operations and validation logic
  • Utils: Core utility functions and error handling
  • Config: Configuration loading and validation
  • Services: Business logic and service composition

Testing Principles

  • Unit Tests: Test individual functions in isolation
  • Mock Dependencies: Use mocks for external dependencies
  • Edge Cases: Test boundary conditions and error scenarios
  • Performance: Include benchmark tests for critical paths
  • Coverage: Aim for >80% overall test coverage

Production Deployment

  • Health Checks: Built-in health check endpoints with database connectivity
  • Graceful Shutdown: Proper signal handling and cleanup
  • Structured Logging: JSON-formatted logs with correlation IDs
  • Metrics: Request/response metrics and monitoring
  • Security: JWT authentication, rate limiting, CORS
  • Database: Connection pooling, migrations, error handling
  • Monitoring: Health endpoints, structured logging, metrics

Contributing

  1. Follow Go coding standards and best practices
  2. Add comprehensive tests for new functionality
  3. Maintain or improve test coverage
  4. Update documentation and examples
  5. Use conventional commit messages
  6. Test edge cases and error scenarios

License

This package is open-source and available under the MIT license. See LICENSE for more details.

About

Go gRPC + REST service template with clean architecture and comprehensive testing. Supports dual APIs, middleware, PostgreSQL, JWT auth, and extensive test coverage.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors