Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Go DDD Template

An opinionated, production-shaped boilerplate for REST APIs in Go, built around Domain-Driven Design layering. It ships with authentication, user CRUD, file uploads, migrations, seeding, validation, and a background worker. Replace the sample User/File domains with your own.

Stack

Concern Library / Tool
Language Go 1.26
HTTP Fiber v3
ORM GORM + PostgreSQL
Migrations pgx v5 (raw SQL, versioned files)
Dependency injection samber/do v2
Auth golang-jwt/jwt v5 (HS256)
Password hashing bcrypt
Refresh-token hashing SHA-256
Validation go-playground/validator v10
API collection Bruno (docs/)

What's included

  • Strict DDD layering — domain, application, infrastructure, and presentation packages with a one-way dependency rule.
  • Auth boilerplate — login, me, refresh-token rotation, logout, JWT middleware.
  • User module — create, paginated list, get by ID, partial update, delete.
  • File module — multipart upload, owner-scoped list/get/download/delete, MIME and size limits, local disk storage behind a port.
  • Persistence model layer — GORM models stay in internal/infra, domain entities stay framework-free.
  • Repository errors — persistence translates GORM's not-found error into repository.ErrNotFound.
  • Unit of Work — multi-repository writes run in a single transaction.
  • Handler helpers — typed bind helpers and centralized error-to-HTTP mapping.
  • Validation — Fiber's StructValidator wired to go-playground/validator.
  • Migrations — up/down/fresh commands with an advisory lock.
  • Seeding — JSON seed files plus optional initial admin creation.
  • Background worker — periodic refresh-token cleanup.
  • Ops scaffolding — Dockerfile, Docker Compose, GitHub Actions, .env.example.
  • API docs — Bruno collection under docs/.

See ARCHITECTURE.md for the layer rules, request flow, and conventions.

Getting started

1. Configure

cp .env.example .env

Fill in the database credentials and JWT_SECRET.

2. Run migrations

go run main.go --migrate-up

3. Seed (optional)

go run main.go --seed

The sample users are [email protected] and [email protected], both with password password123.

4. Start the server

go run main.go
# or explicitly
go run main.go --serve

The server listens on http://127.0.0.1:8888 by default. Commands can be combined:

go run main.go --migrate-up --seed --serve

Environment

Variable Required Description
DB_USER Yes PostgreSQL username
DB_HOST Yes PostgreSQL host (use db inside Docker Compose)
DB_NAME Yes Database name
DB_PORT Yes Database port
JWT_SECRET Yes Secret used to sign access tokens
DB_PASS No Database password
DB_SSLMODE No GORM defaults to prefer, migrations to require; use disable for local Docker
DB_TIMEZONE No Loads time.Local and sets GORM's NowFunc; defaults to UTC
GOLANG_PORT No HTTP port, default 8888
APP_MODE No prod skips JSON seed files
APP_ENV No localhost binds 0.0.0.0:<port>, otherwise :<port>
PRINT_ROUTES No Print registered routes on startup when true
SEED_PATH No Seed directory, default seeds
SEED_INITIAL_ADMIN No Create the initial admin when true
INITIAL_ADMIN_NAME No Initial admin name, default Admin
INITIAL_ADMIN_EMAIL No Initial admin email
INITIAL_ADMIN_PASSWORD No Initial admin password
REFRESH_TOKEN_CLEANUP_WORKER_DISABLED No Disable the cleanup worker when true
REFRESH_TOKEN_CLEANUP_INTERVAL No Cleanup interval, default 1h
STORAGE_PATH No Upload directory, default ./uploads
UPLOAD_MAX_BYTES No Max upload size, default 10485760
UPLOAD_ALLOWED_MIME_TYPES No Comma-separated MIME allowlist; empty allows all

CLI reference

go run main.go [options]

Options:
  --serve           Start the HTTP server; default when no options are given
  --migrate-up      Apply all pending migrations
  --migrate-down    Roll back the latest migration
  --migrate-fresh   Roll back all migrations, then re-apply from scratch
  --seed            Seed the database

Create a paired migration with:

python3 create_migration.py add_example_table

This creates internal/database/NNNN_add_example_table.up.sql and .down.sql.

API

Protected endpoints require:

Authorization: Bearer <access_token>

Access tokens expire after 5 minutes. Refresh tokens expire after 24 hours and are rotated on every refresh.

Health

Method Path Access Description
GET /livez Public Liveness check

Auth

Method Path Access Description
POST /api/login Public Login and return access + refresh tokens
POST /api/refresh Public Rotate tokens using the request-body refresh token
GET /api/me Login Current user profile
POST /api/logout Login Revoke all refresh tokens for the current user

Users

Method Path Access Description
POST /api/user/ Login Create a user
GET /api/user/ Login List users
GET /api/user/:id Login Get a user by ID
PUT /api/user/:id Login Partially update a user
DELETE /api/user/:id Login Delete a user

Files

All file endpoints are scoped to the authenticated owner.

Method Path Access Description
POST /api/file/ Login Upload a file (multipart/form-data, field file)
GET /api/file/ Login List the current user's files
GET /api/file/:id Login Get file metadata
GET /api/file/:id/download Login Download file bytes
DELETE /api/file/:id Login Delete a file

The sample user endpoints require authentication but do not implement role-based authorization. Add a role/claim and middleware when your domain needs it.

Response envelope

Successful response:

{
  "message": "success get data",
  "data": {
    "id": 1,
    "name": "Admin",
    "email": "[email protected]",
    "created_at": "2026-01-01 12:00:00"
  }
}

Paginated response:

{
  "message": "success get data",
  "data": [],
  "meta": {
    "limit": 10,
    "page": 0,
    "totalData": 0,
    "totalPage": 0
  }
}

Failed response:

{
  "message": "failed process request",
  "error": "user not found"
}

Pagination

List endpoints accept page, limit, sort, sortBy, filter, and filterBy.

  • page is zero-based (offset = page * limit).
  • limit defaults to 10.
  • sort accepts asc or desc.
  • sortBy and filterBy are whitelisted per use case, so user input is never interpolated directly into SQL.

Docker

Set DB_HOST=db and DB_SSLMODE=disable in .env, then run:

docker compose up --build

The image runs migrations, seeds, and starts the server. PostgreSQL data and uploaded files are kept in named volumes.

Project layout

.
|-- cmd/                     # CLI entry points, wiring, migrations, seeding
|-- internal/
|   |-- app/                 # use cases, app DTOs, ports, typed errors
|   |-- database/            # versioned SQL migrations
|   |-- domain/              # entities, repository interfaces, value objects
|   |-- infra/               # GORM, JWT, bcrypt, storage, workers
|   `-- presentation/        # Fiber handlers, routes, middleware, HTTP DTOs
|-- seeds/                   # JSON seed data
|-- docs/                    # Bruno API collection
|-- main.go
|-- Dockerfile
`-- docker-compose.yml

Adding a feature

  1. Add the entity in internal/domain/entity.
  2. Add the repository interface in internal/domain/repository.
  3. Add application inputs/outputs in internal/app/dto.
  4. Add the use case in internal/app/usecase.
  5. Add the GORM model in internal/infra/persistence/model and implement the repository in internal/infra/persistence.
  6. Add HTTP DTOs in internal/presentation/dto, a handler, and a route file.
  7. Register repositories, use cases, and routes in cmd/serve.go.
  8. Add a paired migration and, if needed, a seed file.

Testing

go test ./...

Keep use-case tests free of HTTP, database, filesystem, and environment dependencies by mocking the repository and port interfaces.

Notes

This template is intentionally small but opinionated. It does not include role-based access control, audit logging, multi-tenancy, or an OpenAPI specification; add those only when a project needs them.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages