README
ΒΆ

Go REST API Boilerplate
Grab it and Go β a best-practice layered structure REST API starter kit in Go with JWT, PostgreSQL, Docker, and Swagger.
π Start building in under 2 minutes β’ π Fully documented β’ π§ͺ 100% tested β’ π³ Docker ready
Quick Start β’ Features β’ Documentation β’ Examples
π― Looking to Build a REST API in Go?
You need a REST API project with Go and you're looking for:
- β¨ Best-practice clean architecture that scales with your team
- π οΈ CLI tools ready to go - migrations, linting, testing, all configured
- π Production-ready structure - not a toy project, but battle-tested patterns
- π Real documentation - not just comments, but guides and examples
- π³ Docker-first development - consistent environments, zero "works on my machine"
- β‘ Hot-reload that actually works - see changes in 2 seconds, not 20
Stop spending days setting up. This boilerplate gives you everything you need to start building features in minutes, not hours. Real authentication, real database migrations, real tests - all wired up and ready to extend.
Perfect for:
- π Starting new Go projects without the setup headache
- π Learning Go web development with production-quality examples
- ποΈ Building APIs that need to scale and be maintained
- π₯ Team projects where consistency and standards matter
π Quick Start
Get your API running in under 2 minutes:
Prerequisites
- Docker and Docker Compose
- Git
π‘ Want to run without Docker? See the Manual Setup Guide in the documentation.
One-Command Setup β‘
git clone https://github.com/vahiiiid/go-rest-api-boilerplate.git
cd go-rest-api-boilerplate
make quick-start
π Done! Your API is now running at:
- API Base URL: http://localhost:8080/api/v1
- Swagger UI: http://localhost:8080/swagger/index.html
- Health Check: http://localhost:8080/health
Explore Your API π§ͺ
Interactive Swagger Documentation:
Open http://localhost:8080/swagger/index.html to explore and test all endpoints interactively.
Or Use Postman:
Import the pre-configured collection from api/postman_collection.json with example requests and tests.
Quick Test
# Check health
curl http://localhost:8080/health
# Register a user
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"name": "Alice Smith",
"email": "alice@example.com",
"password": "secret123"
}'
π Ready to Build Your Own Features?
π Development Guide - Learn how to add models, routes, and handlers
π‘ TODO List Example - Complete step-by-step tutorial implementing a feature from scratch
β¨ Features
- β JWT Authentication - Secure token-based auth (HS256)
- β User Management - Complete CRUD with validation
- β PostgreSQL + GORM - Robust database with ORM
- β Docker Development - Hot-reload with Air (~2 sec feedback)
- β Docker Production - Optimized multi-stage builds
- β Swagger/OpenAPI - Interactive API documentation
- β Database Migrations - Version-controlled schema changes with CLI tools
- β Automated Testing - Unit & integration tests
- β GitHub Actions CI - Automated linting and testing
- β Make Commands - Simplified workflow automation
- β Postman Collection - Pre-configured API tests
- β Clean Architecture - Layered, maintainable structure
- β Security Best Practices - Bcrypt hashing, input validation
- β CORS Support - Configurable cross-origin requests
- β Request Logging - Configurable structured JSON logging with request tracking
π Table of Contents
π» Development
With Docker (Recommended) π³
The easiest way to develop with hot-reload and zero setup:
# Start everything
make quick-start
# Or manually
make up
# Edit code in your IDE
# Changes auto-reload in ~2 seconds! β¨
# View logs
make logs
# Stop containers
make down
Features:
- π₯ Hot-reload - Code changes reflect in ~2 seconds (powered by Air)
- π¦ Volume mounts - Edit code in your IDE, runs in container
- ποΈ PostgreSQL - Database on internal Docker network
- π All tools pre-installed - No Go installation needed on host
Development Workflow
# Start containers
make up
# Run tests
make test
# Check code quality
make lint
# Fix linting issues
make lint-fix
# Generate/update Swagger docs
make swag
# Database migrations
make migrate-create NAME=add_new_table
make migrate-up
make migrate-down
make migrate-version
# View logs
make logs
# Stop containers
make down
Available Make Commands
Run make help to see all commands. Key commands:
make quick-start # Complete automated setup
make up # Start development containers
make down # Stop containers
make test # Run tests (auto-detects environment)
make lint # Run linter (auto-detects environment)
make swag # Generate Swagger docs (auto-detects environment)
make migrate-up # Run migrations (auto-detects environment)
make build-binary # Build Go binary directly (requires Go on host)
make run-binary # Build and run binary directly (requires Go on host)
π‘ Most commands auto-detect whether to run in Docker or on your host machine!
Without Docker (Native Development)
Want to run without Docker? You'll need Go 1.23+ installed on your machine.
See the Manual Setup Guide for detailed instructions on:
- Installing Go and development tools
- Setting up PostgreSQL locally
- Building and running the binary directly
- Manual migration commands
Quick native build:
make build-binary # Build binary to bin/server
make run-binary # Build and run (requires PostgreSQL on localhost)
π Production
Overview
GRAB provides optimized production builds with:
- β Multi-stage Docker builds (minimal image size)
- β No development dependencies
- β No mounted volumes
- β Production-ready configuration
- β Health checks
Simple Deployment (VPS/Server)
# Clone repository on your server
git clone https://github.com/vahiiiid/go-rest-api-boilerplate.git
cd go-rest-api-boilerplate
# Install development tools (needed for Swagger generation)
make install-tools
# Create production environment file
cp .env.example .env
nano .env # Edit with production values (database, JWT secret, etc.)
# Generate API documentation
make swag
# Start production containers
make docker-up-prod
Production Configuration
Update .env with production values:
ENV=production
PORT=8080
DB_HOST=your-db-host
DB_PORT=5432
DB_USER=your-db-user
DB_PASSWORD=your-strong-password
DB_NAME=your-db-name
JWT_SECRET=your-very-strong-random-secret
JWT_TTL_HOURS=24
Docker Production Build
# Build production image
docker build -t grab-api:latest .
# Run production container
docker run -p 8080:8080 --env-file .env grab-api:latest
Cloud Deployment
GRAB is ready to deploy to:
- AWS ECS/Fargate - Container orchestration
- Google Cloud Run - Serverless containers
- Azure Container Instances - Managed containers
- DigitalOcean App Platform - Platform-as-a-service
- Kubernetes - Self-managed orchestration
- Any VPS - Using Docker Compose
For detailed deployment guides, database migrations, and Docker production setup, see the Setup Guide and Docker Guide.
π API Documentation
Swagger UI
Interactive API documentation is available at:
http://localhost:8080/swagger/index.html
Try endpoints directly from your browser with the built-in "Try it out" feature.
Postman Collection
Import the pre-configured Postman collection with example requests and tests:
api/postman_collection.json
Includes:
- Pre-configured requests for all endpoints
- Environment variables
- Automated tests
- Example payloads
API Endpoints
Authentication
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/v1/auth/register |
Register new user |
| POST | /api/v1/auth/login |
Login user |
Users (Protected)
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | /api/v1/users/:id |
Get user by ID | β |
| PUT | /api/v1/users/:id |
Update user | β |
| DELETE | /api/v1/users/:id |
Delete user | β |
Health
| Method | Endpoint | Description |
|---|---|---|
| GET | /health |
Health check |
Example Requests
Register User:
curl -X POST http://localhost:8080/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"password": "securepass123"
}'
Login:
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "securepass123"
}'
For more examples, see the Quick Reference Guide.
π§ͺ Testing
Run Tests
# Run all tests
make test
# Run tests with coverage
make test-coverage
# Run tests in verbose mode
go test ./... -v
Test Coverage
The project includes:
- β Unit tests - Handler, service, repository layers
- β Integration tests - Full request/response cycle
- β In-memory SQLite - No external dependencies for tests
- β Test fixtures - Reusable test data
- β
HTTP mocking - Using
httptestpackage
Test Suites:
TestRegisterHandler- User registration flowsTestLoginHandler- Authentication flowsTestHealthEndpoint- Health check validation
Continuous Integration
GitHub Actions automatically runs on every push:
- β Run all tests
- β
Check code with
go vet - β
Run
golangci-lint - β Generate coverage reports
See .github/workflows/ci.yml for CI configuration.
π Documentation
Full API documentation, usage guides, and tutorials are maintained in a separate repository:
π Documentation Site
Complete, searchable documentation site featuring:
- π Getting Started guides
- π» Development tutorials with examples
- ποΈ Architecture overview
- π³ Docker deployment guides
- π API reference with Swagger
- ποΈ Database migration guides
π¦ Documentation Repository
π go-rest-api-docs
The documentation repository includes:
- Complete setup and deployment guides
- Step-by-step development tutorials
- TODO list implementation example
- Best practices and patterns
- Troubleshooting guides
- Contributing guidelines
π€ Contributing to Documentation
To contribute to the documentation:
- Visit the docs repository
- Follow the contributing guidelines
- Submit pull requests for improvements
For contributing to the codebase, see CONTRIBUTING.md
ποΈ Project Structure
go-rest-api-boilerplate/
βββ api/
β βββ docs/ # Swagger documentation (auto-generated)
β β βββ docs.go # Swagger Go package
β β βββ swagger.json # OpenAPI JSON spec
β β βββ swagger.yaml # OpenAPI YAML spec
β βββ postman_collection.json # Postman API tests with examples
βββ bin/ # Compiled binaries (gitignored)
β βββ server # Built Go binary (from make build-binary)
βββ cmd/
β βββ server/
β βββ main.go # Application entry point
βββ configs/
β βββ config.yaml # Configuration file example
βββ docs/ # Documentation site (MkDocs)
β βββ docs/ # Documentation source files
β β βββ DEVELOPMENT_GUIDE.md # Development tutorial
β β βββ DOCKER.md # Docker setup guide
β β βββ LOGGING.md # Logging configuration
β β βββ MIGRATIONS_GUIDE.md # Database migration guide
β β βββ SETUP.md # Manual setup instructions
β β βββ SWAGGER.md # API documentation guide
β β βββ TESTING.md # Testing guide
β β βββ TODO_EXAMPLE.md # Complete feature implementation example
β β βββ images/ # Documentation images and assets
β βββ site/ # Generated documentation site
β βββ mkdocs.yml # MkDocs configuration
β βββ requirements.txt # Python dependencies for docs
βββ internal/ # Private application code
β βββ auth/ # Authentication & authorization
β β βββ dto.go # JWT claims & auth DTOs
β β βββ middleware.go # JWT middleware
β β βββ service.go # Token generation & validation
β βββ config/ # Configuration management
β β βββ config.go # Config structs and loading logic
β β βββ config_test.go # Configuration tests
β βββ db/
β β βββ db.go # Database connection setup (GORM)
β βββ middleware/ # HTTP middleware
β β βββ logger.go # Request logging middleware
β β βββ logger_test.go # Logger middleware tests
β β βββ README.md # Middleware documentation
β βββ server/
β β βββ router.go # Route definitions & middleware
β βββ user/ # User domain (example feature)
β βββ dto.go # Request/Response DTOs
β βββ handler.go # HTTP handlers with Swagger annotations
β βββ model.go # GORM database model
β βββ repository.go # Data access layer (CRUD)
β βββ service.go # Business logic layer
βββ migrations/ # Database migration files (SQL)
β βββ 000001_create_users_table.up.sql
β βββ 000001_create_users_table.down.sql
βββ scripts/ # Helper automation scripts
β βββ quick-start.sh # One-command Docker setup
βββ tests/
β βββ handler_test.go # Integration tests (httptest + SQLite)
β βββ README.md # Testing guide
βββ tmp/ # Air hot-reload temp files (gitignored)
βββ .air.toml # Hot-reload configuration (Air)
βββ .gitignore # Git ignore rules
βββ .golangci.yml # Linter configuration
βββ .github/
β βββ workflows/
β βββ ci.yml # GitHub Actions CI/CD pipeline
βββ CHANGELOG.md # Version history (SemVer)
βββ CONTRIBUTING.md # Contribution guidelines
βββ docker-compose.yml # Development with hot-reload & volumes
βββ docker-compose.prod.yml # Production optimized (no volumes)
βββ Dockerfile # Multi-stage build (dev + prod)
β # Dev: All tools pre-installed
β # Prod: Minimal Alpine image
βββ go.mod # Go module dependencies
βββ go.sum # Dependency checksums
βββ LICENSE # MIT License
βββ Makefile # Build automation & shortcuts
β # Auto-detects Docker/host environment
βββ README.md # This file
βββ server.log # Application logs (gitignored)
Key Highlights
- π³ Docker-First: All dev tools pre-installed in container (swag, golangci-lint, migrate, air)
- π₯ Hot-Reload: Code changes reflect in ~2 seconds via Air + volume mounts
- ποΈ Migrations: SQL-based migrations with golang-migrate
- π Clean Architecture: Clear separation: Handler β Service β Repository
- π§ͺ Fully Tested: Unit & integration tests with in-memory SQLite
- βοΈ Auto-Detection: Make commands work in Docker or on host automatically
π Documentation: All guides, tutorials, and API docs are in a separate repository and published at vahiiiid.github.io/go-rest-api-docs
ποΈ Architecture
GRAB follows clean architecture principles with clear separation of concerns:
Layers
βββββββββββββββββββββββββββββββββββββββ
β Handler Layer β β HTTP handlers, request/response
β (internal/user/handler.go) β validation, error handling
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Service Layer β β Business logic, orchestration
β (internal/user/service.go) β transactions, domain rules
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Repository Layer β β Data access, CRUD operations
β (internal/user/repository.go) β database queries
βββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββ
β Database (PostgreSQL) β β Data persistence
βββββββββββββββββββββββββββββββββββββββ
Key Principles
- β Separation of Concerns - Each layer has a single responsibility
- β Dependency Injection - Loose coupling between layers
- β Testability - Easy to mock and test each layer
- β Maintainability - Clear structure, easy to navigate
- β Scalability - Easy to extend with new features
Want to Build Your Own Features?
The Development Guide provides a complete walkthrough of this architecture with a real TODO list implementation showing you exactly how to:
- Add new models and database tables
- Create repositories, services, and handlers
- Register routes and add Swagger documentation
- Follow the same patterns used in the user management system
π Security Features
- Password Hashing - Bcrypt with configurable cost (default: 10)
- JWT Tokens - Secure token generation and validation (HS256)
- Input Validation - Request validation using Gin binding tags
- SQL Injection Protection - GORM parameterized queries
- CORS - Configurable cross-origin resource sharing
- Rate Limiting - (Add via middleware - see docs)
- Environment Variables - Sensitive data never hardcoded
β οΈ Production Checklist:
- Change
JWT_SECRETto a strong, random value - Use strong database passwords
- Enable HTTPS/TLS
- Configure proper CORS origins
- Set up rate limiting
- Enable database connection encryption
- Regular dependency updates
π€ Contributing
Contributions are welcome! See CONTRIBUTING.md for:
- Code style guidelines
- Pull request process
- Testing requirements
- Commit conventions
Quick Guidelines
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Run tests and linter (
make lint && make test) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
π Changelog
See CHANGELOG.md for a detailed history of changes.
Current Version: v1.0.0 - Initial stable release
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Acknowledgments
Built with these amazing tools:
- Gin - HTTP web framework
- GORM - ORM library
- golang-jwt - JWT implementation
- swaggo - Swagger documentation
- Air - Hot-reload for development
- golang-migrate - Database migrations
π§ Support
- π Check the documentation
- π Report bugs
- π¬ Ask questions
- β Star this repo if you find it helpful!
Made with β€οΈ for the Go community
β Star this repo if you find it useful!