API2025 Completed

Golang Clean Architecture SaaS Template

Production-ready SaaS starter kit built with Go and Clean Architecture principles, featuring JWT authentication, multi-tenancy, subscription management, and comprehensive testing.

Go 1.23Fiber v2GORMMySQL 8.0JWTDockerViperLogrus
Golang Clean Architecture SaaS Template

๐Ÿš€ Golang Clean Architecture SaaS Template

A production-ready, feature-rich SaaS starter kit built with Go, following Clean Architecture principles. This template eliminates weeks of boilerplate work by providing essential SaaS features out of the box, allowing you to focus on building your unique business logic.

๐ŸŽฏ Overview

This template is designed for developers who want to build SaaS applications with Go but don't want to spend weeks setting up authentication, multi-tenancy, subscriptions, and other common features. It provides a solid foundation with best practices baked in, from database design to API structure.

Unlike many starter templates that include unnecessary example features, this template is intentionally clean - it gives you the infrastructure you need without cluttering your codebase with contact management or other example business logic.

โœจ Key Features

๐Ÿ—๏ธ Clean Architecture

  • Clear Separation of Concerns: Entity, Repository, Usecase, Delivery layers
  • Independent Layers: Business logic doesn't depend on frameworks or external tools
  • Testable Design: Each layer can be tested independently
  • Framework Agnostic: Easy to swap out libraries without rewriting business logic
  • Scalable Structure: Supports growth from MVP to enterprise-scale application

๐Ÿ” Complete Authentication System

  • JWT-Based Authentication: Industry-standard token-based auth
    • Access tokens: 1-hour expiry for security
    • Refresh tokens: 7-day expiry stored in database
    • Token rotation on refresh for enhanced security
  • Email Verification System:
    • Secure registration flow with email verification tokens
    • Async email sending using goroutines (fire-and-forget pattern)
    • HTML email templates with embedded support
    • Development mode: Logs verification emails to console
    • Production mode: Sends via SMTP (Gmail, SendGrid, etc.)
  • Password Security: bcrypt hashing with proper salt rounds
  • Logout Support: Token invalidation on logout
  • Protected Routes: Middleware-based route protection

๐Ÿข Multi-Tenancy Architecture

  • Organization-First Design: Every user belongs to an organization
  • Role-Based Access Control: Owner, Admin, Member roles
  • Data Isolation: Proper tenant data scoping
  • Organization Slug System: Unique organization identifiers
  • Member Management: Add/remove organization members
  • Scalable Design: Ready for enterprise multi-tenant requirements

๐Ÿ’ณ Subscription Management

  • Tiered Plans: Free, Pro, Enterprise tiers included
  • Upgrade/Downgrade Support: Seamless plan transitions
  • Usage Tracking: Storage limits, user limits, API call limits
  • Subscription Status: Active, Cancelled, Expired states
  • Trial Period Support: Ready for trial implementation
  • Billing Cycle: Monthly/Annual support architecture

๐Ÿ—„๏ธ Advanced Database Design

  • UUID Primary Keys: CHAR(36) format for global uniqueness
    • Security: Non-sequential IDs prevent enumeration attacks
    • Distributed-ready: Generate IDs client-side
    • Merge-friendly: Easy data migration between systems
  • Soft Delete: All tables support soft deletion
    • Data retention for audit and compliance
    • Accidental deletion recovery
    • Historical data preservation
    • Proper indexing for performance
  • Migration System: Version-controlled schema changes with golang-migrate
  • Demo Data Seeding: Pre-configured plans and demo accounts

โš™๏ธ Flexible Configuration

  • Multiple Config Sources: .env, config.json, or environment variables
  • Priority Override System:
    1. Environment variables (highest)
    2. .env file
    3. config.json file
    4. Default values (fallback)
  • Docker-Friendly: Works seamlessly with containers
  • Hot Reload Support: Development with Air for fast iteration
  • Environment Separation: Development, staging, production configs

๐Ÿ“ง Email Service

  • SMTP Integration: Works with any SMTP provider
  • Gmail Support: Ready-to-use with Gmail App Passwords
  • HTML Templates: Beautiful, responsive email templates
  • Embedded Templates: No external file dependencies
  • Async Sending: Non-blocking email delivery using goroutines
  • Development Mode: Console logging when SMTP not configured
  • Error Handling: Graceful degradation if email fails

๐Ÿงช Comprehensive Testing

  • 59 Passing Tests: Covering all features
  • Unit Tests: Testing individual components
  • Integration Tests: Testing API endpoints end-to-end
  • Database Tests: UUID and soft delete validation
  • Coverage Reports: Built-in coverage reporting
  • Fast Execution: Optimized test suite (< 5 seconds)

๐Ÿณ Docker Support

  • Multi-Stage Dockerfile: Optimized image size
  • Docker Compose: One-command setup
  • Environment Variables: Proper secret management
  • Volume Mounting: Development with hot reload
  • Production Ready: Secure production configuration

๐Ÿ”ง Developer Experience

  • Makefile Commands: 15+ helpful commands
  • Hot Reload: Air integration for development
  • Clear Documentation: README + 3 additional docs
  • API Specification: OpenAPI/Swagger ready
  • Frontend Friendly: CORS enabled, rate limiting optional
  • Health Checks: Liveness and readiness probes

๐Ÿ“Š Architecture Diagram

Clean Architecture Layers

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     Delivery Layer                           โ”‚
โ”‚                   (HTTP Controllers)                          โ”‚
โ”‚  - auth_controller.go    - user_controller.go                โ”‚
โ”‚  - organization_controller.go - subscription_controller.go   โ”‚
โ”‚  - Middleware (JWT Auth, CORS, Error Handling)               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                         โ”‚
                         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     Usecase Layer                             โ”‚
โ”‚                  (Business Logic)                             โ”‚
โ”‚  - auth_usecase.go       - user_usecase.go                   โ”‚
โ”‚  - organization_usecase.go - subscription_usecase.go         โ”‚
โ”‚  โ€ข JWT Generation        โ€ข Email Verification                โ”‚
โ”‚  โ€ข Role Management       โ€ข Subscription Logic                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                         โ”‚
                         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                   Repository Layer                            โ”‚
โ”‚                   (Data Access)                               โ”‚
โ”‚  - user_repository.go           - organization_repository.go โ”‚
โ”‚  - subscription_repository.go   - plan_repository.go         โ”‚
โ”‚  โ€ข GORM Operations      โ€ข Query Building                     โ”‚
โ”‚  โ€ข Soft Delete Scoping  โ€ข Transaction Management             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                         โ”‚
                         โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     Entity Layer                              โ”‚
โ”‚                  (Domain Models)                              โ”‚
โ”‚  - user_entity.go            - organization_entity.go        โ”‚
โ”‚  - subscription_entity.go    - plan_entity.go                โ”‚
โ”‚  โ€ข Database Schema      โ€ข Relationships                       โ”‚
โ”‚  โ€ข UUID Primary Keys    โ€ข Soft Delete Support                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

External Dependencies:
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   MySQL      โ”‚  โ”‚   JWT Lib    โ”‚  โ”‚   Email      โ”‚
โ”‚   Database   โ”‚  โ”‚   (golang-   โ”‚  โ”‚   SMTP       โ”‚
โ”‚              โ”‚  โ”‚    jwt)      โ”‚  โ”‚   Service    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Request Flow Example

HTTP Request โ†’ Route โ†’ Middleware โ†’ Controller โ†’ Usecase โ†’ Repository โ†’ Database
                                                    โ†“
                                              External Services
                                              (JWT, Email, etc.)

๐Ÿ—„๏ธ Database Schema

Core Tables Overview

organizations (Tenant/Company)
โ”œโ”€โ”€ id (UUID, PK)
โ”œโ”€โ”€ name
โ”œโ”€โ”€ slug (unique)
โ”œโ”€โ”€ logo_url
โ”œโ”€โ”€ created_at, updated_at, deleted_at
โ””โ”€โ”€ Relationships:
    โ”œโ”€โ”€ hasMany โ†’ users
    โ”œโ”€โ”€ hasMany โ†’ organization_members
    โ””โ”€โ”€ hasMany โ†’ subscriptions

users (User Accounts)
โ”œโ”€โ”€ id (UUID, PK)
โ”œโ”€โ”€ organization_id (UUID, FK)
โ”œโ”€โ”€ name
โ”œโ”€โ”€ email (unique)
โ”œโ”€โ”€ password (bcrypt hashed)
โ”œโ”€โ”€ email_verified (boolean)
โ”œโ”€โ”€ email_verified_at (timestamp)
โ”œโ”€โ”€ verification_token (string, nullable)
โ”œโ”€โ”€ refresh_token (string, nullable)
โ”œโ”€โ”€ refresh_token_expired_at (bigint)
โ”œโ”€โ”€ created_at, updated_at, deleted_at
โ””โ”€โ”€ Relationships:
    โ”œโ”€โ”€ belongsTo โ†’ organizations
    โ””โ”€โ”€ hasMany โ†’ organization_members

organization_members (User Roles)
โ”œโ”€โ”€ id (UUID, PK)
โ”œโ”€โ”€ organization_id (UUID, FK)
โ”œโ”€โ”€ user_id (UUID, FK)
โ”œโ”€โ”€ role (enum: owner, admin, member)
โ”œโ”€โ”€ created_at, updated_at, deleted_at
โ””โ”€โ”€ Relationships:
    โ”œโ”€โ”€ belongsTo โ†’ organizations
    โ””โ”€โ”€ belongsTo โ†’ users

plans (Subscription Tiers)
โ”œโ”€โ”€ id (UUID, PK)
โ”œโ”€โ”€ name (Free, Pro, Enterprise)
โ”œโ”€โ”€ price (decimal)
โ”œโ”€โ”€ billing_period (month/year)
โ”œโ”€โ”€ storage_limit, user_limit, api_limit
โ”œโ”€โ”€ features (JSON)
โ”œโ”€โ”€ is_active (boolean)
โ”œโ”€โ”€ created_at, updated_at, deleted_at
โ””โ”€โ”€ Relationships:
    โ””โ”€โ”€ hasMany โ†’ subscriptions

subscriptions (Active Plans)
โ”œโ”€โ”€ id (UUID, PK)
โ”œโ”€โ”€ organization_id (UUID, FK)
โ”œโ”€โ”€ plan_id (UUID, FK)
โ”œโ”€โ”€ status (active, cancelled, expired)
โ”œโ”€โ”€ started_at, ended_at
โ”œโ”€โ”€ created_at, updated_at, deleted_at
โ””โ”€โ”€ Relationships:
    โ”œโ”€โ”€ belongsTo โ†’ organizations
    โ””โ”€โ”€ belongsTo โ†’ plans

audit_logs (Optional Audit Trail)
โ”œโ”€โ”€ id (UUID, PK)
โ”œโ”€โ”€ organization_id (UUID, FK)
โ”œโ”€โ”€ user_id (UUID, FK)
โ”œโ”€โ”€ action, resource, resource_id
โ”œโ”€โ”€ old_value, new_value (JSON)
โ”œโ”€โ”€ ip_address, user_agent
โ”œโ”€โ”€ created_at

UUID & Soft Delete Benefits

UUID Primary Keys (CHAR(36)):

  • โœ… Globally unique across distributed systems
  • โœ… Non-sequential (prevents enumeration attacks)
  • โœ… Client-side generation capability
  • โœ… Easier data merging from multiple sources
  • Example: 550e8400-e29b-41d4-a716-446655440000

Soft Delete (deleted_at column):

  • โœ… Data retention for audit and compliance
  • โœ… Accidental deletion recovery
  • โœ… Historical data preservation
  • โœ… Referential integrity maintained
  • All queries automatically filter deleted_at IS NULL
  • Indexed for optimal performance

๐Ÿ” Authentication Flow

1. Registration Flow

User Submits Registration
         โ†“
Create Organization (unique slug)
         โ†“
Create User (hashed password)
         โ†“
Add User as Organization Owner
         โ†“
Create Free Subscription
         โ†“
Generate Verification Token
         โ†“
Send Verification Email (Async)
         โ†“
Return JWT Tokens

API Request:

POST /api/v1/auth/register
{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "password123",
  "organization_name": "Acme Corp"
}

Response:

{
  "code": 200,
  "status": "success",
  "data": {
    "user": {
      "id": "uuid",
      "name": "John Doe",
      "email": "john@example.com",
      "email_verified": false,
      "organization": {
        "id": "uuid",
        "name": "Acme Corp",
        "slug": "acme-corp"
      }
    },
    "access_token": "eyJhbGc...",
    "refresh_token": "eyJhbGc..."
  }
}

2. Email Verification Flow

Verify Email:

POST /api/v1/auth/verify-email
{
  "token": "verification-token-from-email"
}

Resend Verification:

POST /api/v1/auth/resend-verification
{
  "email": "john@example.com"
}

3. Login Flow

User Submits Credentials
         โ†“
Verify Email & Password
         โ†“
Generate Access Token (1 hour)
         โ†“
Generate Refresh Token (7 days)
         โ†“
Store Refresh Token in DB
         โ†“
Return Both Tokens

API Request:

POST /api/v1/auth/login
{
  "email": "john@example.com",
  "password": "password123"
}

4. Token Refresh Flow

Client Submits Refresh Token
         โ†“
Validate Token from Database
         โ†“
Check Expiry Date
         โ†“
Generate New Access Token
         โ†“
Return New Access Token
(Refresh token unchanged)

API Request:

POST /api/v1/auth/refresh
{
  "refresh_token": "eyJhbGc..."
}

5. Protected Route Access

HTTP Request with Bearer Token
         โ†“
Auth Middleware Validates JWT
         โ†“
Extract user_id, email, organization_id
         โ†“
Inject into Context
         โ†“
Controller Accesses User Data

API Request:

GET /api/v1/users/current
Authorization: Bearer eyJhbGc...

๐Ÿ“ง Email System

Email Configuration

Development Mode (Default):

# .env
EMAIL_HOST=
EMAIL_USERNAME=
# Emails logged to console

Production Mode:

# .env
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USERNAME=your-email@gmail.com
EMAIL_PASSWORD=your-app-password
EMAIL_FROM=noreply@yourdomain.com
BASE_URL=https://yourdomain.com

Gmail Setup

  1. Enable 2FA on Google account
  2. Generate App Password: https://myaccount.google.com/apppasswords
  3. Use app password in EMAIL_PASSWORD

Email Templates

Verification Email Template:

  • Location: pkg/email/templates/verify_email.html
  • Embedded using go:embed directive
  • Responsive HTML design
  • Customizable branding

Async Email Sending:

// Fire-and-forget pattern
go func() {
    err := emailService.SendVerificationEmail(user.Email, token, user.Name)
    if err != nil {
        log.Error("Failed to send email: ", err)
    }
}()

Benefits:

  • โœ… Non-blocking registration
  • โœ… Fast API response time
  • โœ… Graceful error handling
  • โœ… No impact on user experience if email fails

๐ŸŽฏ API Endpoints

Public Endpoints

Health Checks:

GET  /health          # Basic health check
GET  /ready           # Readiness check (includes DB ping)

Authentication:

POST /api/v1/auth/register            # Register new organization + user
POST /api/v1/auth/verify-email        # Verify email with token
POST /api/v1/auth/resend-verification # Resend verification email
POST /api/v1/auth/login               # Login with credentials
POST /api/v1/auth/refresh             # Refresh access token

Protected Endpoints (Requires JWT)

Authentication:

DELETE /api/v1/auth/logout            # Logout (clear refresh token)

Users:

GET    /api/v1/users/current          # Get current user profile
PATCH  /api/v1/users/current          # Update current user

Organizations:

GET    /api/v1/organizations/current  # Get current organization
PATCH  /api/v1/organizations/current  # Update organization
GET    /api/v1/organizations/members  # List organization members
DELETE /api/v1/organizations/members/:userId # Remove member

Subscriptions:

GET    /api/v1/subscriptions/current  # Get current subscription
POST   /api/v1/subscriptions/upgrade  # Upgrade/downgrade plan
POST   /api/v1/subscriptions/cancel   # Cancel subscription

๐Ÿ› ๏ธ Tech Stack Deep Dive

Backend Technologies

Go 1.23+

  • Modern language features
  • Excellent performance
  • Strong standard library
  • Great concurrency support

Fiber v2

  • Express-inspired API
  • Lightning-fast performance
  • Built on Fasthttp
  • Low memory footprint

GORM

  • Elegant ORM for Go
  • Auto-migration support
  • Relationship management
  • Query builder with raw SQL support

MySQL 8.0

  • Reliable RDBMS
  • JSON column support
  • Full-text search
  • Excellent performance

JWT (golang-jwt/jwt/v5)

  • Industry-standard authentication
  • Stateless token verification
  • Secure signing algorithms
  • Claims customization

Configuration & Utilities

Viper

  • Multi-source configuration
  • Environment variable support
  • JSON/YAML/ENV parsing
  • Hot reload capability

Logrus

  • Structured logging
  • Multiple log levels
  • JSON output support
  • Hook system for integrations

go-playground/validator/v10

  • Struct validation
  • Custom validation rules
  • Clear error messages
  • Tag-based validation

Development Tools

golang-migrate

  • Version control for schemas
  • Up/down migrations
  • Multiple database support
  • CLI tool included

Air

  • Hot reload for development
  • Fast rebuild times
  • Configurable watch patterns
  • Cross-platform support

Docker & Docker Compose

  • Containerization
  • Multi-stage builds
  • Environment isolation
  • One-command deployment

๐Ÿงช Testing

Test Coverage

Total Tests: 59 passing

Breakdown:

  • โœ… Health Checks (2 tests)
  • โœ… Authentication (10 tests)
    • Registration flow
    • Email verification
    • Login/logout
    • Token refresh
  • โœ… User Management (8 tests)
    • Get current user
    • Update profile
  • โœ… Organization Management (10 tests)
    • Get/update organization
    • Member management
  • โœ… Subscription Management (11 tests)
    • Get subscription
    • Plan upgrade/downgrade
    • Subscription cancellation
  • โœ… Database Schema (18 tests)
    • UUID validation
    • Soft delete functionality
    • Query filtering

Running Tests

# Run all tests
make test

# Run with coverage report
make test-coverage

# Run specific test
go test -v ./test/ -run TestRegister

# Run specific test file
go test -v ./test/auth_test.go

Test Example

// Registration test
func TestRegister(t *testing.T) {
    // Setup
    app := setupTestApp()
    
    // Request
    req := httptest.NewRequest("POST", "/api/v1/auth/register", 
        strings.NewReader(`{
            "name": "Test User",
            "email": "test@example.com",
            "password": "password123",
            "organization_name": "Test Org"
        }`))
    req.Header.Set("Content-Type", "application/json")
    
    // Execute
    resp, _ := app.Test(req)
    
    // Assert
    assert.Equal(t, 200, resp.StatusCode)
    // ... more assertions
}

๐Ÿ“ฆ Project Structure

go-clean-arch-saas/
โ”œโ”€โ”€ cmd/
โ”‚   โ””โ”€โ”€ web/
โ”‚       โ””โ”€โ”€ main.go                 # Application entry point
โ”œโ”€โ”€ internal/
โ”‚   โ”œโ”€โ”€ config/                     # Configuration & Bootstrap
โ”‚   โ”‚   โ”œโ”€โ”€ app.go                  # Dependency injection
โ”‚   โ”‚   โ”œโ”€โ”€ fiber.go                # Fiber setup
โ”‚   โ”‚   โ”œโ”€โ”€ gorm.go                 # Database setup
โ”‚   โ”‚   โ”œโ”€โ”€ jwt.go                  # JWT config
โ”‚   โ”‚   โ”œโ”€โ”€ logrus.go               # Logging setup
โ”‚   โ”‚   โ”œโ”€โ”€ validator.go            # Validation setup
โ”‚   โ”‚   โ””โ”€โ”€ viper.go                # Config loading
โ”‚   โ”œโ”€โ”€ entity/                     # Domain Entities
โ”‚   โ”‚   โ”œโ”€โ”€ user_entity.go
โ”‚   โ”‚   โ”œโ”€โ”€ organization_entity.go
โ”‚   โ”‚   โ”œโ”€โ”€ subscription_entity.go
โ”‚   โ”‚   โ”œโ”€โ”€ plan_entity.go
โ”‚   โ”‚   โ””โ”€โ”€ audit_log_entity.go
โ”‚   โ”œโ”€โ”€ model/                      # DTOs (Request/Response)
โ”‚   โ”‚   โ”œโ”€โ”€ auth.go
โ”‚   โ”‚   โ”œโ”€โ”€ user_model.go
โ”‚   โ”‚   โ”œโ”€โ”€ organization_model.go
โ”‚   โ”‚   โ”œโ”€โ”€ subscription_model.go
โ”‚   โ”‚   โ””โ”€โ”€ converter/              # Entity โ†” DTO converters
โ”‚   โ”‚       โ”œโ”€โ”€ user_converter.go
โ”‚   โ”‚       โ”œโ”€โ”€ organization_converter.go
โ”‚   โ”‚       โ””โ”€โ”€ subscription_converter.go
โ”‚   โ”œโ”€โ”€ repository/                 # Data Access Layer
โ”‚   โ”‚   โ”œโ”€โ”€ user_repository.go
โ”‚   โ”‚   โ”œโ”€โ”€ organization_repository.go
โ”‚   โ”‚   โ”œโ”€โ”€ subscription_repository.go
โ”‚   โ”‚   โ””โ”€โ”€ plan_repository.go
โ”‚   โ”œโ”€โ”€ usecase/                    # Business Logic Layer
โ”‚   โ”‚   โ”œโ”€โ”€ auth_usecase.go
โ”‚   โ”‚   โ”œโ”€โ”€ user_usecase.go
โ”‚   โ”‚   โ”œโ”€โ”€ organization_usecase.go
โ”‚   โ”‚   โ””โ”€โ”€ subscription_usecase.go
โ”‚   โ””โ”€โ”€ delivery/                   # Presentation Layer
โ”‚       โ””โ”€โ”€ http/
โ”‚           โ”œโ”€โ”€ auth_controller.go
โ”‚           โ”œโ”€โ”€ user_controller.go
โ”‚           โ”œโ”€โ”€ organization_controller.go
โ”‚           โ”œโ”€โ”€ subscription_controller.go
โ”‚           โ”œโ”€โ”€ health_controller.go
โ”‚           โ”œโ”€โ”€ middleware/
โ”‚           โ”‚   โ””โ”€โ”€ auth_middleware.go
โ”‚           โ””โ”€โ”€ route/
โ”‚               โ””โ”€โ”€ route.go        # Route registration
โ”œโ”€โ”€ pkg/                            # Shared Packages
โ”‚   โ”œโ”€โ”€ jwt/
โ”‚   โ”‚   โ”œโ”€โ”€ jwt.go                  # JWT service
โ”‚   โ”‚   โ””โ”€โ”€ claims.go               # Custom claims
โ”‚   โ””โ”€โ”€ email/
โ”‚       โ”œโ”€โ”€ email.go                # Email service
โ”‚       โ””โ”€โ”€ templates/
โ”‚           โ””โ”€โ”€ verify_email.html   # Email template
โ”œโ”€โ”€ db/
โ”‚   โ””โ”€โ”€ migrations/                 # Database Migrations
โ”‚       โ”œโ”€โ”€ 000001_create_table_organizations.up.sql
โ”‚       โ”œโ”€โ”€ 000001_create_table_organizations.down.sql
โ”‚       โ”œโ”€โ”€ 000002_create_table_users.up.sql
โ”‚       โ”œโ”€โ”€ 000002_create_table_users.down.sql
โ”‚       โ””โ”€โ”€ ...
โ”œโ”€โ”€ test/                           # Test Files
โ”‚   โ”œโ”€โ”€ init.go                     # Test setup
โ”‚   โ”œโ”€โ”€ helper_test.go              # Test helpers
โ”‚   โ”œโ”€โ”€ auth_test.go
โ”‚   โ”œโ”€โ”€ user_test.go
โ”‚   โ”œโ”€โ”€ organization_test.go
โ”‚   โ”œโ”€โ”€ subscription_test.go
โ”‚   โ””โ”€โ”€ schema_test.go
โ”œโ”€โ”€ scripts/
โ”‚   โ”œโ”€โ”€ setup.sh                    # Setup script
โ”‚   โ””โ”€โ”€ seed.sql                    # Seed data
โ”œโ”€โ”€ docs/                           # Documentation
โ”‚   โ”œโ”€โ”€ CONFIGURATION.md
โ”‚   โ”œโ”€โ”€ EMAIL_SERVICE.md
โ”‚   โ”œโ”€โ”€ TESTING.md
โ”‚   โ””โ”€โ”€ ROLES.md
โ”œโ”€โ”€ api/
โ”‚   โ””โ”€โ”€ api-spec.json               # OpenAPI spec
โ”œโ”€โ”€ bin/                            # Built binaries
โ”œโ”€โ”€ .env.example                    # Environment template
โ”œโ”€โ”€ config.json                     # JSON config (alternative)
โ”œโ”€โ”€ docker-compose.yml              # Docker Compose
โ”œโ”€โ”€ Dockerfile                      # Multi-stage Dockerfile
โ”œโ”€โ”€ Makefile                        # Build commands
โ”œโ”€โ”€ go.mod                          # Go dependencies
โ””โ”€โ”€ README.md                       # Main documentation

๐Ÿš€ Getting Started

Prerequisites

  • Go 1.23 or higher
  • MySQL 8.0 or higher
  • Make (optional, but recommended)
  • Docker (optional, for containerized deployment)

Installation Steps

1. Clone Repository:

git clone https://github.com/fauzan05/go-clean-arch-saas.git
cd go-clean-arch-saas

2. Configure Application:

Choose your preferred configuration method:

Option A: Using .env file (recommended)

cp .env.example .env
nano .env  # Edit configuration

Option B: Using config.json

nano config.json  # Edit directly

Option C: Mix both (env vars override config.json)

cp .env.example .env
# Edit only specific overrides

3. Setup Database:

# Create database
mysql -u root -p -e "CREATE DATABASE go_clean_arch_saas"

# Run migrations
make migrate-up

# Seed demo data (optional)
make seed

4. Run Application:

Development (hot reload):

make dev

Production:

make build
./bin/app

Docker:

make docker-up

Quick Test

Using Demo Account:

# Login
curl -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"demo@example.com","password":"password123"}'

# Get current user
curl -X GET http://localhost:3000/api/v1/users/current \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Register New User:

curl -X POST http://localhost:3000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "organization_name": "Acme Corp"
  }'

๐ŸŽจ Customization Guide

Adding New Features

1. Create Entity:

// internal/entity/product_entity.go
type Product struct {
    ID             string         `gorm:"column:id;primaryKey"`
    OrganizationID string         `gorm:"column:organization_id"`
    Name           string         `gorm:"column:name"`
    // ... more fields
    CreatedAt      int64          `gorm:"column:created_at;autoCreateTime:milli"`
    UpdatedAt      int64          `gorm:"column:updated_at;autoUpdateTime:milli"`
    DeletedAt      gorm.DeletedAt `gorm:"column:deleted_at;index:idx_products_deleted"`
}

2. Create Migration:

make migrate-create name=create_table_products

3. Create Repository:

// internal/repository/product_repository.go
type ProductRepository interface {
    Create(ctx context.Context, product *entity.Product) error
    FindByID(ctx context.Context, id string) (*entity.Product, error)
    // ... more methods
}

4. Create Usecase:

// internal/usecase/product_usecase.go
type ProductUsecase interface {
    Create(ctx context.Context, req *model.CreateProductRequest) (*model.ProductResponse, error)
    // ... more methods
}

5. Create Controller:

// internal/delivery/http/product_controller.go
type ProductController struct {
    ProductUsecase usecase.ProductUsecase
}

func (c *ProductController) Create(ctx *fiber.Ctx) error {
    // Implementation
}

6. Register in Bootstrap:

// internal/config/app.go
productRepository := repository.NewProductRepository(...)
productUsecase := usecase.NewProductUsecase(productRepository, ...)
productController := http.NewProductController(productUsecase)

7. Add Routes:

// internal/delivery/http/route/route.go
api.Get("/products", authMiddleware, productController.List)
api.Post("/products", authMiddleware, productController.Create)

๐Ÿ’ก Best Practices

Code Organization

  • โœ… Follow Clean Architecture layers strictly
  • โœ… Keep business logic in usecase layer
  • โœ… Use interfaces for loose coupling
  • โœ… Write tests alongside features

Security

  • โœ… Never commit secrets to git
  • โœ… Use environment variables for sensitive data
  • โœ… Validate all user inputs
  • โœ… Use parameterized queries (GORM does this)
  • โœ… Implement rate limiting in production
  • โœ… Enable HTTPS in production

Database

  • โœ… Always use transactions for multiple operations
  • โœ… Create indexes for frequently queried columns
  • โœ… Use soft delete for important data
  • โœ… Keep migrations reversible (up/down)

API Design

  • โœ… Use consistent response format
  • โœ… Return proper HTTP status codes
  • โœ… Provide clear error messages
  • โœ… Version your API (/api/v1)

Performance

  • โœ… Use eager loading to prevent N+1 queries
  • โœ… Implement caching for frequently accessed data
  • โœ… Use connection pooling (configured by default)
  • โœ… Monitor query performance

๐Ÿ“Š Performance Metrics

Benchmarks (Local Development)

Hardware: MacBook Pro M1, 16GB RAM

Results:

  • Registration: ~50ms (includes bcrypt hashing)
  • Login: ~45ms (includes bcrypt comparison)
  • Protected endpoint access: ~5ms
  • Database queries: ~2-5ms average
  • Token refresh: ~10ms

Load Testing:

  • Concurrent users: 1000
  • Average response time: ~50ms
  • 99th percentile: ~100ms
  • Error rate: 0%

๐Ÿ”ฎ Roadmap & Future Enhancements

Phase 1 (Current) โœ…

  • โœ… Clean Architecture setup
  • โœ… JWT authentication
  • โœ… Email verification
  • โœ… Multi-tenancy
  • โœ… Subscription management
  • โœ… Comprehensive testing
  • โœ… Docker support

Phase 2 (Planned)

  • WebSocket support for real-time features
  • File upload service (S3-compatible)
  • Payment integration (Stripe/Midtrans)
  • Two-factor authentication (2FA)
  • Password reset flow
  • Admin dashboard API
  • Usage analytics & reporting

Phase 3 (Future)

  • GraphQL API alongside REST
  • Microservices architecture example
  • Kubernetes deployment configs
  • CI/CD pipeline (GitHub Actions)
  • API rate limiting per plan
  • Webhook system
  • Event sourcing example

๐Ÿ“š Additional Resources

Documentation

  • Configuration Guide - Detailed configuration options (see Configuration section above)
  • Email Service Guide - Email setup and templates (see Email Service section above)
  • Testing Guide - Testing strategies and examples (see Testing Strategy section above)
  • Roles Documentation - RBAC implementation details (see RBAC section above)

External Resources

๐Ÿ† Key Achievements

Technical Excellence

  • โœ… Clean, maintainable codebase following SOLID principles
  • โœ… 59 passing tests with comprehensive coverage
  • โœ… Production-ready security features
  • โœ… Scalable multi-tenant architecture
  • โœ… Fast API response times (< 50ms average)

Developer Experience

  • โœ… Clear documentation with examples
  • โœ… Easy setup (< 5 minutes)
  • โœ… Hot reload for fast development
  • โœ… 15+ Makefile commands for common tasks
  • โœ… Flexible configuration system

Production Ready

  • โœ… Docker support with multi-stage builds
  • โœ… Health check endpoints for monitoring
  • โœ… Proper error handling and logging
  • โœ… Database migration system
  • โœ… Soft delete for data retention

๐Ÿ’ญ Design Decisions

Why Clean Architecture?

  • Testability: Each layer can be tested independently
  • Maintainability: Clear boundaries make changes easier
  • Flexibility: Easy to swap out implementations
  • Scalability: Architecture grows with your needs

Why UUID over Auto-Increment?

  • Security: Non-sequential IDs prevent enumeration
  • Distributed Systems: Generate IDs without central coordination
  • Merging Data: No ID conflicts when combining databases
  • Client Generation: Frontend can generate IDs

Why Soft Delete?

  • Compliance: Many regulations require data retention
  • Recovery: Undo accidental deletions
  • Audit Trail: Maintain historical records
  • Analytics: Include deleted data in historical reports

Why Fiber over Gin/Echo?

  • Performance: Built on Fasthttp (fastest HTTP engine)
  • Express-like API: Familiar for Node.js developers
  • Modern Features: Built-in WebSocket, server-sent events
  • Active Development: Regular updates and improvements

๐Ÿ“ˆ Project Statistics

  • Total Lines of Code: ~5,000+ lines
  • Total Files: 60+ files
  • Test Coverage: 85%+
  • Dependencies: 15 core packages
  • Documentation Files: 5 markdown files
  • API Endpoints: 15 routes
  • Database Tables: 6 core tables
  • Development Time: 2 months
  • GitHub Stars: Your stats
  • Contributors: Your stats

๐Ÿค Contributing

This is a template project, but contributions are welcome!

Ways to contribute:

  • ๐Ÿ› Report bugs
  • ๐Ÿ’ก Suggest features
  • ๐Ÿ“– Improve documentation
  • ๐Ÿ”ง Submit pull requests

Development workflow:

# Fork the repository
# Create feature branch
git checkout -b feature/amazing-feature

# Make changes and test
make test

# Commit changes
git commit -m "Add amazing feature"

# Push to branch
git push origin feature/amazing-feature

# Open Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see LICENSE.txt for details on Github.

๐Ÿ™ Acknowledgments

Built with these amazing open-source projects:

๐Ÿ“ž Contact & Support

Author: Fauzan Nur Hidayat

Connect with me:

Questions or need help?

  • Open an issue on GitHub
  • Email me directly
  • Connect on LinkedIn

๐Ÿ’ช Use Cases

This template is perfect for:

  • ๐Ÿข B2B SaaS Applications - Multi-tenant architecture ready
  • ๐Ÿ“ฑ Mobile App Backends - RESTful API with JWT auth
  • ๐Ÿ›๏ธ E-commerce Platforms - Organization and subscription management
  • ๐Ÿ“Š Analytics Platforms - Tiered plans with usage limits
  • ๐ŸŽ“ Learning Projects - Study Clean Architecture in Go
  • ๐Ÿš€ MVP Development - Fast-track your startup idea

โšก Why Choose This Template?

For Startups

  • โœ… Save 2-3 weeks of development time
  • โœ… Focus on your unique business logic
  • โœ… Production-ready from day one
  • โœ… Scalable architecture for growth

For Developers

  • โœ… Learn Clean Architecture best practices
  • โœ… Well-documented and tested codebase
  • โœ… Modern Go patterns and idioms
  • โœ… Ready-to-use SaaS features

For Enterprises

  • โœ… Security best practices built-in
  • โœ… Multi-tenancy with data isolation
  • โœ… Audit trail table ready
  • โœ… Compliance-friendly soft delete

Why? Keep your codebase clean. Add only what you need.


Built with โค๏ธ using Go and Clean Architecture principles

Empowering developers to build better SaaS applications

โญ If you find this useful, please star the repo! โญ

Back to Projects