Skip to content

openframebox/goinit-simplified-ddd

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Init - Simplified DDD Boilerplate

A production-ready Go boilerplate implementing a simplified Domain-Driven Design (DDD) architecture. This project provides a clean, maintainable structure for building scalable web applications with best practices baked in.

Tech Stack

  • Web Framework: Fiber v2
  • CLI Framework: Cobra
  • ORM: GORM with PostgreSQL
  • Authentication: GoAuth v2 JWT-based auth with access/refresh tokens
  • Queue: GoQueue Redis-backed job queue
  • Cache: GoCache Redis caching
  • Email: GoMail SMTP with template support
  • Storage: GoStorage Local disk and S3-compatible storage
  • Logging: Logrus
  • Validation: Govalidator Custom validator with field-level validation

Features

  • JWT Authentication - Register, login, logout, token refresh, and profile endpoints
  • User Management - Full CRUD operations with pagination
  • Database Migrations - Version-controlled schema migrations
  • Background Workers - Async job processing with Redis queue
  • Email Service - SMTP integration with HTML templates
  • File Storage - Upload to local disk or S3-compatible storage
  • Caching - Redis-backed caching with TTL support
  • Event-Driven Architecture - Pub/sub event system for decoupled components
  • Input Validation - Request validation with custom error messages
  • Structured Logging - Configurable log levels, formats, and outputs

Architecture

This boilerplate follows a 4-layer simplified DDD architecture:

┌─────────────────────────────────────────────────────────────────┐
│                      Interface Layer                            │
│              (HTTP Handlers, Middleware, Routes)                │
├─────────────────────────────────────────────────────────────────┤
│                     Application Layer                           │
│              (Services, DTOs, Events, Use Cases)                │
├─────────────────────────────────────────────────────────────────┤
│                    Infrastructure Layer                         │
│    (Repositories, Database, Cache, Queue, Email, Storage)       │
├─────────────────────────────────────────────────────────────────┤
│                       Domain Layer                              │
│           (Entities, Interfaces, Domain Errors)                 │
└─────────────────────────────────────────────────────────────────┘

Layer Responsibilities

Layer Purpose Dependencies
Domain Core business entities, repository interfaces, domain errors None
Application Business logic orchestration, use cases, DTOs, events Domain
Infrastructure External services implementation (DB, cache, queue, email) Domain
Interface HTTP handlers, request/response handling, middleware Application

Project Structure

.
├── cmd/
│   └── main.go                          # Application entry point
├── internal/
│   ├── component/
│   │   ├── domain/                      # Domain layer
│   │   │   ├── auth/                    # Auth entities & interfaces
│   │   │   ├── user/                    # User entities & interfaces
│   │   │   └── shared/                  # Shared domain utilities
│   │   ├── application/                 # Application layer
│   │   │   ├── auth/                    # Auth service & DTOs
│   │   │   ├── user/                    # User service, DTOs & events
│   │   │   └── shared/                  # Shared application utilities
│   │   ├── infrastructure/              # Infrastructure layer
│   │   │   ├── persistence/postgres/    # Database models, repos, migrations
│   │   │   ├── authenticator/           # JWT authentication
│   │   │   ├── cache/                   # Redis caching
│   │   │   ├── email/                   # Email service
│   │   │   ├── event/                   # Event bus
│   │   │   ├── logger/                  # Logging setup
│   │   │   ├── queue/                   # Queue/job processing
│   │   │   ├── security/                # Password hashing
│   │   │   ├── storage/                 # File storage (local/S3)
│   │   │   └── validator/               # Input validation
│   │   └── interface/
│   │       └── http/
│   │           ├── handler/             # HTTP endpoint handlers
│   │           └── middleware/          # HTTP middleware
│   ├── container/                       # Dependency injection
│   ├── configuration/                   # Configuration management
│   └── helper/                          # Utility helpers
├── storage/
│   ├── logs/                            # Application logs
│   └── uploads/                         # Uploaded files
├── .env                                 # Environment configuration
├── go.mod                               # Go module definition
└── go.sum                               # Go module checksums

Prerequisites

  • Go 1.21 or higher
  • PostgreSQL 12 or higher
  • Redis 6 or higher
  • MinIO (optional) - For S3-compatible local storage
  • MailHog (optional) - For local email testing

Setup

1. Clone the repository

git clone <repository-url>
cd goinit-simplified-ddd

2. Install dependencies

go mod download

3. Configure environment

Copy and edit the environment file:

cp .env.example .env
# Or edit the existing .env file

Update the .env file with your configuration (see Configuration section).

4. Create the database

# Using psql
createdb goinit_simplified_ddd

5. Run migrations

go run cmd/main.go migration migrate

Running the Application

Start the HTTP Server

go run cmd/main.go start server

The server will start on the configured host and port (default: localhost:8080).

Start the Background Worker

go run cmd/main.go start worker

The worker processes background jobs like sending emails.

Build and Run

# Build the binary
go build -o app cmd/main.go

# Run server
./app start server

# Run worker
./app start worker

CLI Commands

Server Commands

Command Description
start server Start the HTTP server
start worker Start the background job worker

Migration Commands

Command Description
migration list List all migrations and their status
migration migrate Run all pending migrations
migration rollback --step 1 Rollback the last migration batch
migration reset Rollback all migrations
migration clean Drop all tables and re-run migrations
migration create --name <name> --dir <dir> Create a new migration file

Examples:

# Run migrations
go run cmd/main.go migration migrate

# Rollback last migration
go run cmd/main.go migration rollback --step 1

# Create new migration
go run cmd/main.go migration create --name create_posts_table --dir internal/component/infrastructure/persistence/postgres/migration

# List migration status
go run cmd/main.go migration list

API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /api/v1/auth/register Register a new user No
POST /api/v1/auth/login Login and get tokens No
POST /api/v1/auth/logout Logout and invalidate refresh token Yes
POST /api/v1/auth/refresh Refresh access token Yes
GET /api/v1/auth/profile Get current user profile Yes

Users

Method Endpoint Description Auth Required
GET /api/v1/users List users with pagination Yes
GET /api/v1/users/:id Get user by ID Yes
POST /api/v1/users Create a new user Yes
PUT /api/v1/users/:id Update user Yes
DELETE /api/v1/users/:id Delete user Yes

File Upload

Method Endpoint Description Auth Required
POST /api/v1/file/upload/local Upload file to local storage No
POST /api/v1/file/upload/s3 Upload file to S3 storage No

Request Examples

Register:

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

Login:

curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "johndoe", "password": "password123"}'

Authenticated Request:

curl http://localhost:8080/api/v1/auth/profile \
  -H "Authorization: Bearer <access_token>"

Configuration

All configuration is managed through environment variables in the .env file.

Application

Variable Description Default
APP_NAME Application name GoInit Simplified DDD
APP_CLI_NAME CLI command name app

HTTP Server

Variable Description Default
HTTP_HOST Server host localhost
HTTP_PORT Server port 8080
HTTP_PRINT_ROUTES Print routes on startup true

Database (PostgreSQL)

Variable Description Default
DB_HOST Database host localhost
DB_PORT Database port 5432
DB_USER Database user postgres
DB_PASSWORD Database password postgres
DB_DATABASE Database name goinit_simplified_ddd
DB_SSLMODE SSL mode disable
DB_TIMEZONE Database timezone UTC
DB_SCHEMA Database schema public
DB_MAX_OPEN_CONNECTIONS Max open connections 100
DB_MAX_IDLE_CONNECTIONS Max idle connections 10
DB_LOG_QUERY Log SQL queries false

Security (JWT)

Variable Description Default
JWT_SECRET JWT signing secret -
JWT_TOKEN_ISSUER Token issuer goinit
JWT_ACCESS_TOKEN_EXPIRES_IN Access token TTL 5m
JWT_REFRESH_TOKEN_EXPIRES_IN Refresh token TTL 1h
JWT_AUDIENCE Token audience goinit

Queue (Redis)

Variable Description Default
QUEUE_REDIS_HOST Redis host localhost
QUEUE_REDIS_PORT Redis port 6379
QUEUE_REDIS_DB Redis database 0
QUEUE_REDIS_PASSWORD Redis password -

Cache (Redis)

Variable Description Default
CACHE_REDIS_HOST Redis host localhost
CACHE_REDIS_PORT Redis port 6379
CACHE_REDIS_DB Redis database 1
CACHE_REDIS_PASSWORD Redis password -

Email (SMTP)

Variable Description Default
EMAIL_SMTP_HOST SMTP host localhost
EMAIL_SMTP_PORT SMTP port 1025
EMAIL_SMTP_USER SMTP username -
EMAIL_SMTP_PASS SMTP password -
EMAIL_USE_SSL Use SSL false
EMAIL_USE_TLS Use TLS false

Storage

Variable Description Default
STORAGE_LOCAL_DISK_PATH Local storage path storage/uploads
STORAGE_S3_ENDPOINT S3 endpoint URL -
STORAGE_S3_REGION S3 region us-east-1
STORAGE_S3_ACCESS_KEY S3 access key -
STORAGE_S3_SECRET_KEY S3 secret key -
STORAGE_S3_BUCKET S3 bucket name -
STORAGE_S3_USE_PATH_STYLE Use path-style URLs true

Logger

Variable Description Default
LOG_LEVEL Log level (debug, info, warn, error) info
LOG_FORMAT Log format (text, json) text
LOG_OUTPUT Output (console, file, both) both
LOG_FILE_PATH Log file path storage/logs/app.log

Development

Adding a New Domain

  1. Create domain entities and interfaces in internal/component/domain/<name>/
  2. Create application services and DTOs in internal/component/application/<name>/
  3. Implement repositories in internal/component/infrastructure/persistence/postgres/
  4. Create HTTP handlers in internal/component/interface/http/handler/
  5. Register routes in internal/container/application_http.go
  6. Wire dependencies in internal/container/application.go

Creating Migrations

go run cmd/main.go migration create --name <migration_name> --dir <migration_dir>

This creates a new migration file in internal/component/infrastructure/persistence/postgres/migration/.

Adding Event Listeners

  1. Create events in internal/component/application/<domain>/event.go
  2. Create listener in internal/component/infrastructure/event/
  3. Register listener in internal/container/application_event.go

License

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

About

A production-ready Go boilerplate implementing a simplified Domain-Driven Design (DDD) architecture.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors