Help us shape the future of Go! Take the 2026 Go Developer Survey

go-rest-api-boilerplate

module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2025 License: MIT

README ΒΆ

GRAB Logo

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

Explore the docs Β»

Version CI Go Report Card Go Version Docker PostgreSQL Documentation PRs Welcome GitHub Stars

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

πŸ’‘ 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
Quick Start Demo

πŸŽ‰ Done! Your API is now running at:

Explore Your API πŸ§ͺ

Interactive Swagger Documentation:

Swagger UI

Open http://localhost:8080/swagger/index.html to explore and test all endpoints interactively.

Or Use Postman:

Postman Collection

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

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 httptest package

Test Suites:

  • TestRegisterHandler - User registration flows
  • TestLoginHandler - Authentication flows
  • TestHealthEndpoint - 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

🌐 View Full Documentation

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:

  1. Visit the docs repository
  2. Follow the contributing guidelines
  3. 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

πŸ“– View Full Documentation


πŸ” 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_SECRET to 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

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Run tests and linter (make lint && make test)
  5. Commit your changes (git commit -m 'feat: add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. 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:


πŸ“§ Support


Made with ❀️ for the Go community

⭐ Star this repo if you find it useful!

Directories ΒΆ

Path Synopsis
cmd
server command
internal
db

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL