Skip to content
/ go-template Public template

A production-ready template for building Go services using clean architecture principles, featuring JWT authentication, PostgreSQL with Prisma, comprehensive testing, and Docker support.

License

Notifications You must be signed in to change notification settings

ibhanu/go-template

Repository files navigation

Go Clean Template

Build Status Go Report Card Go Reference Release codecov Go Version License Issues Pull Requests Last Commit

A production-ready template for creating Go services following clean architecture principles. This template provides a robust foundation for building scalable, maintainable, and well-tested microservices in Go.

Why This Template? πŸ€”

Building production-grade microservices requires more than just writing code. You need:

  • A solid architectural foundation
  • Security best practices
  • Comprehensive testing
  • Performance optimization
  • Developer-friendly tooling

This template provides all these essentials out of the box, saving you weeks of setup time and helping you follow established best practices.

Features πŸš€

  • Clean Architecture with detailed examples
  • JWT Authentication & Role-Based Access Controlx
  • End-to-End Encryption for requests/responses
  • PostgreSQL with Prisma ORM
  • Graceful Shutdown
  • Structured Logging with Logrus
  • Hot Reload Development
  • Docker with Docker Compose
  • Make commands for development
  • Comprehensive test examples
  • Swagger documentation
  • Rate Limiting

Quick Start πŸš€

1. Get the Template

# Clone the repository
git clone https://github.com/ibhanu/go-template.git

# Create your project
mkdir -p your-project && cd your-project
cp -r ../go-clean-template/* .
rm -rf .git && git init

2. Configure Environment

# Copy and edit environment variables
cp .env.example .env

# Edit .env with your settings:
# - Database credentials
# - JWT secret
# - API configurations

3. Setup and Run

# Install dependencies and setup database
make setup

# Generate Prisma client
make prisma-generate

# Start development server with hot reload
make dev

Visit http://localhost:8080/swagger/ to explore the API.

Project Structure πŸ“‚

.
β”œβ”€β”€ internal/                 # Application code
β”‚   β”œβ”€β”€ domain/              # Enterprise business rules
β”‚   β”‚   β”œβ”€β”€ entity/          # Business entities
β”‚   β”‚   β”œβ”€β”€ repository/      # Repository interfaces
β”‚   β”‚   └── constants/       # Domain constants
β”‚   β”œβ”€β”€ application/         # Application business rules
β”‚   β”‚   └── usecase/        # Use case implementations
β”‚   β”œβ”€β”€ infrastructure/      # External tools and frameworks
β”‚   β”‚   β”œβ”€β”€ config/         # Configuration
β”‚   β”‚   β”œβ”€β”€ middleware/     # HTTP middleware
β”‚   β”‚   β”œβ”€β”€ repository/     # Repository implementations
β”‚   β”‚   └── server/        # HTTP server setup
β”‚   └── interface/          # Interface adapters
β”‚       └── handler/        # HTTP handlers
β”œβ”€β”€ prisma/                 # Database schema and client
β”œβ”€β”€ scripts/               # Utility scripts
└── docs/                  # Documentation

Architecture Overview πŸ—

Clean Architecture Layers

  1. Domain Layer (innermost)

    • Contains enterprise business rules
    • Pure Go without external dependencies
    • Defines interfaces and entities
  2. Application Layer

    • Implements use cases
    • Orchestrates domain objects
    • Contains business logic
  3. Interface Layer

    • Adapts data between layers
    • Handles HTTP requests
    • Manages serialization
  4. Infrastructure Layer (outermost)

    • Implements interfaces
    • Integrates external services
    • Manages technical concerns

Clean Architecture

Development Commands πŸ› 

Core Commands

# Development
make setup           # Initialize project
make dev             # Run with hot reload
make build           # Build binary
make run             # Run binary
make clean           # Clean build files

# Testing
make test            # Run all tests
make test-coverage   # Run tests with coverage
make test-race       # Run tests with race detection
make benchmark       # Run benchmark tests

# Code Quality
make lint           # Run linters
make fmt            # Format code
make vet            # Run go vet
make cyclo          # Check cyclomatic complexity

# Database
make db-init        # Initialize database
make db-migrate     # Run migrations
make prisma-generate # Generate Prisma client
make prisma-studio  # Open Prisma Studio

# Docker
make docker-build   # Build image
make docker-push    # Push to registry
make deploy         # Deploy with docker-compose
make docker-logs    # View container logs

Advanced Commands

# Testing
make test-integration  # Run integration tests
make test-e2e         # Run end-to-end tests
make test-stress      # Run stress tests

# Documentation
make docs             # Generate documentation
make swagger          # Generate Swagger specs

# Maintenance
make clean-docker     # Clean Docker resources
make reset-db         # Reset database
make generate-keys    # Generate JWT keys

API Documentation πŸ“š

Authentication

All protected routes require a JWT token in the Authorization header:

Authorization: Bearer <your-token>

Public Routes

Register User

POST /api/public/users/register
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "securepass",
  "name": "John Doe"
}

Login

POST /api/public/users/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "securepass"
}

Protected Routes

Get User Details

GET /api/private/users/:id
Authorization: Bearer <token>

Update User

PUT /api/private/users/:id
Authorization: Bearer <token>
Content-Type: application/json

{
  "name": "Updated Name",
  "email": "new@example.com"
}

Delete User

DELETE /api/private/users/:id
Authorization: Bearer <token>

Admin Routes

List All Users

GET /api/private/users/admin
Authorization: Bearer <token>

Environment Configuration πŸ”§

# Server Configuration
PORT=8080
ENV=development
LOG_LEVEL=debug
CORS_ALLOWED_ORIGINS=*

# Database Configuration
DATABASE_URL=postgresql://user:pass@localhost:5432/dbname
DB_MAX_CONNECTIONS=100
DB_IDLE_TIMEOUT=300

# Security
JWT_SECRET=your-secret-key
JWT_EXPIRY=24h
ENCRYPTION_KEY=32-byte-encryption-key
RATE_LIMIT=100

Security Considerations πŸ”’

Authentication & Authorization

  • JWT-based authentication
  • Role-based access control (RBAC)
  • Token refresh mechanism
  • Session management

Data Protection

  • Password hashing with bcrypt
  • Request/Response encryption
  • HTTPS enforcement
  • XSS protection
  • CSRF protection

Infrastructure

  • Rate limiting
  • Secure headers
  • Input validation
  • SQL injection prevention
  • Error handling security

Performance Optimization πŸš„

Database

  • Connection pooling
  • Query optimization
  • Indexed lookups
  • Efficient pagination

Application

  • Response caching
  • Compressed responses
  • Optimized routing
  • Memory management

Monitoring

  • Performance metrics
  • Resource utilization
  • Response times
  • Error rates

Error Handling & Logging πŸ”

Error Types

  • Domain errors
  • Application errors
  • Infrastructure errors
  • HTTP errors

Logging

  • Structured logging
  • Log levels
  • Request ID tracking
  • Error context

Testing Strategy βœ…

Unit Tests

  • Domain logic
  • Use cases
  • Utilities
  • Middleware

Integration Tests

  • API endpoints
  • Database operations
  • External services

Performance Tests

  • Load testing
  • Stress testing
  • Benchmarks

Deployment πŸš€

Docker Deployment

# Build and run with Docker Compose
make deploy

# Scale services
docker-compose up -d --scale app=3

# View logs
make docker-compose-logs

Kubernetes Deployment

# Apply Kubernetes manifests
kubectl apply -f k8s/

# Scale deployment
kubectl scale deployment app --replicas=3

# View pods
kubectl get pods

Troubleshooting πŸ”§

Common Issues

  1. Database Connection

    # Check database status
    make db-status
    
    # Reset database
    make reset-db
  2. Permission Issues

    # Fix file permissions
    chmod +x scripts/*
  3. Build Errors

    # Clean and rebuild
    make clean && make build

Contributing 🀝

We welcome contributions! Please read CONTRIBUTING.md for details on:

  • Code of Conduct
  • Pull Request Process
  • Development Guidelines
  • Testing Requirements
  • Documentation Standards

License πŸ“

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments πŸ™