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.
| 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/) |
- 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
StructValidatorwired togo-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.
cp .env.example .envFill in the database credentials and JWT_SECRET.
go run main.go --migrate-upgo run main.go --seedThe sample users are [email protected] and [email protected], both with password password123.
go run main.go
# or explicitly
go run main.go --serveThe server listens on http://127.0.0.1:8888 by default. Commands can be combined:
go run main.go --migrate-up --seed --serve| 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 |
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_tableThis creates internal/database/NNNN_add_example_table.up.sql and .down.sql.
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.
| Method | Path | Access | Description |
|---|---|---|---|
| GET | /livez |
Public | Liveness check |
| 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 |
| 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 |
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.
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"
}List endpoints accept page, limit, sort, sortBy, filter, and filterBy.
pageis zero-based (offset = page * limit).limitdefaults to10.sortacceptsascordesc.sortByandfilterByare whitelisted per use case, so user input is never interpolated directly into SQL.
Set DB_HOST=db and DB_SSLMODE=disable in .env, then run:
docker compose up --buildThe image runs migrations, seeds, and starts the server. PostgreSQL data and uploaded files are kept in named volumes.
.
|-- 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
- Add the entity in
internal/domain/entity. - Add the repository interface in
internal/domain/repository. - Add application inputs/outputs in
internal/app/dto. - Add the use case in
internal/app/usecase. - Add the GORM model in
internal/infra/persistence/modeland implement the repository ininternal/infra/persistence. - Add HTTP DTOs in
internal/presentation/dto, a handler, and a route file. - Register repositories, use cases, and routes in
cmd/serve.go. - Add a paired migration and, if needed, a seed file.
go test ./...Keep use-case tests free of HTTP, database, filesystem, and environment dependencies by mocking the repository and port interfaces.
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.