go-rest-api-boilerplate

module
v1.0.0 Latest Latest
Warning

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

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

README ΒΆ

GRAB Logo

🧩 GRAB

Go REST API Boilerplate

Grab it and Go β€” a clean, lightweight, production-ready REST API starter kit in Go with JWT, PostgreSQL, Docker, and Swagger.

πŸš€ Start building in under 2 minutes β€’ πŸ“š Fully documented β€’ πŸ§ͺ 100% tested β€’ 🐳 Docker ready

Version CI Go Report Card Documentation

✨ 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
  • βœ… Automated Testing - Unit & integration tests
  • βœ… GitHub Actions CI - Automated linting and testing
  • βœ… Make Commands - Simplified workflow automation
  • βœ… Helper Scripts - Quick setup and verification tools
  • βœ… Postman Collection - Pre-configured API tests
  • βœ… Clean Architecture - Layered, maintainable structure
  • βœ… Security Best Practices - Bcrypt hashing, input validation
  • βœ… CORS Support - Configurable cross-origin requests

🎯 Why GRAB?

Stop wasting time on boilerplate. Start building features.

  • ⚑ 2-Minute Setup - One command gets you a fully working API
  • πŸ“š Learn by Example - Complete TODO list tutorial in the docs
  • πŸ”₯ Hot-Reload - See changes in ~2 seconds, no restart needed
  • βœ… Production Ready - Used in real projects, not just a demo
  • πŸ“– Actually Documented - Every feature explained with examples
  • πŸ§ͺ Fully Tested - All endpoints have working tests you can learn from

Perfect for:

  • πŸš€ Starting new Go projects quickly
  • πŸ“– Learning Go web development best practices
  • πŸ—οΈ Building production-ready APIs
  • πŸ‘₯ Team projects with consistent structure

πŸ“‘ Table of Contents


πŸš€ Quick Start

Get up and running in under 2 minutes:

Prerequisites
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:

What Just Happened?

The quick-start command automatically:

  1. βœ… Installed development tools (swag, golangci-lint, migrate, air)
  2. βœ… Verified all prerequisites and dependencies
  3. βœ… Created .env file from template
  4. βœ… Generated Swagger documentation
  5. βœ… Built and started Docker containers
  6. βœ… Ran database migrations (via AutoMigrate)
πŸš€ Ready to Build Your Own Features?

Now that your API is running, learn how to add your own endpoints!

πŸ“– Development Guide - Complete guide showing you how to:

  • Understand the codebase structure
  • Add new models, routes, and handlers
  • Implement CRUD operations
  • Follow best practices

Or if you learn by example, check out the TODO List Example - a complete step-by-step tutorial implementing a TODO feature from scratch!

Visit the documentation site for the full guide!

Try It Out πŸ§ͺ
# 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"
  }'

# Visit Swagger UI for interactive docs
open http://localhost:8080/swagger/index.html

πŸ’» Development

make quick-start

This starts the development environment with:

  • πŸ”₯ 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
  • πŸ“š Swagger - Auto-generated API documentation
Manual Docker Setup

If you prefer to see what's happening step-by-step:

# 1. Install development tools
make install-tools
# or
./scripts/install-tools.sh

# 2. Create environment file
cp .env.example .env

# 3. Generate Swagger docs
make swag
# or
./scripts/init-swagger.sh

# 4. Start containers with hot-reload
docker-compose up --build

That's it! The API will automatically reload when you edit code.

πŸ’‘ Next Step: Check out the Development Guide to learn how to add your own endpoints! It includes a complete TODO list example with all the code you need.

Development Workflow
# Start containers
make docker-up

# Edit code in your IDE
# Changes auto-reload in ~2 seconds! ✨

# Check code quality
make lint

# Run tests
make test

# Generate/update Swagger docs
make swag

# Stop containers
make docker-down

# View logs
docker-compose logs -f app
Available Make Commands
make help              # Show all available commands
make quick-start       # Complete automated setup
make docker-up         # Start development containers
make docker-down       # Stop containers
make lint              # Run linter (golangci-lint)
make lint-fix          # Auto-fix linting issues
make test              # Run all tests
make test-coverage     # Run tests with coverage report
make swag              # Generate Swagger documentation
make migrate-create    # Create new migration file
make migrate-docker-up # Run migrations in container
make verify            # Verify project setup
make install-tools     # Install development tools
Without Docker (Manual Development)

For local development without Docker, see the Setup Guide for detailed instructions on:

  • Installing Go 1.23+
  • Setting up PostgreSQL locally
  • Running the app directly on your machine
  • Manual migration commands

🏭 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 List users (paginated) βœ…
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"
  }'

List Users (with auth):

curl -X GET http://localhost:8080/api/v1/users \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

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
  • TestProtectedEndpoints - Authorization checks
  • 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.json
β”‚   β”‚   └── swagger.yaml
β”‚   └── postman_collection.json    # Postman API tests with examples
β”œβ”€β”€ cmd/
β”‚   └── server/
β”‚       └── main.go                # Application entry point
β”œβ”€β”€ configs/
β”‚   └── config.yaml                # Configuration file example
β”œβ”€β”€ internal/                      # Private application code
β”‚   β”œβ”€β”€ auth/                      # Authentication & authorization
β”‚   β”‚   β”œβ”€β”€ dto.go                 # JWT claims & auth DTOs
β”‚   β”‚   β”œβ”€β”€ middleware.go          # JWT middleware
β”‚   β”‚   └── service.go             # Token generation & validation
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   └── db.go                  # Database connection setup
β”‚   β”œβ”€β”€ server/
β”‚   β”‚   └── router.go              # Route definitions & middleware
β”‚   └── user/                      # User domain (example feature)
β”‚       β”œβ”€β”€ dto.go                 # Request/Response DTOs
β”‚       β”œβ”€β”€ handler.go             # HTTP handlers with Swagger docs
β”‚       β”œβ”€β”€ model.go               # GORM database model
β”‚       β”œβ”€β”€ repository.go          # Data access layer (CRUD)
β”‚       └── service.go             # Business logic layer
β”œβ”€β”€ migrations/                    # Database migration files
β”‚   β”œβ”€β”€ 000001_create_users_table.up.sql
β”‚   └── 000001_create_users_table.down.sql
β”œβ”€β”€ scripts/                       # Helper automation scripts
β”‚   β”œβ”€β”€ install-tools.sh           # Install dev tools (swag, air, etc.)
β”‚   β”œβ”€β”€ quick-start.sh             # One-command setup
β”‚   β”œβ”€β”€ init-swagger.sh            # Generate Swagger docs
β”‚   └── verify-setup.sh            # Verify project setup
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ handler_test.go            # Integration tests (httptest)
β”‚   └── README.md                  # Testing guide
β”œβ”€β”€ .air.toml                      # Hot-reload configuration
β”œβ”€β”€ .env.example                   # Environment variables template
β”œβ”€β”€ .gitignore
β”œβ”€β”€ .golangci.yml                  # Linter configuration
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── ci.yml                 # GitHub Actions CI/CD
β”œβ”€β”€ CHANGELOG.md                   # Version history
β”œβ”€β”€ CONTRIBUTING.md                # Contribution guidelines
β”œβ”€β”€ docker-compose.yml             # Development with hot-reload
β”œβ”€β”€ docker-compose.prod.yml        # Production optimized
β”œβ”€β”€ Dockerfile                     # Multi-stage build (dev + prod)
β”œβ”€β”€ go.mod                         # Go module dependencies
β”œβ”€β”€ go.sum                         # Dependency checksums
β”œβ”€β”€ LICENSE                        # MIT License
β”œβ”€β”€ Makefile                       # Build automation & shortcuts
└── README.md                      # This file

πŸ“š 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