Go hexagonal architecture

From makifbaysal/tasktrooper · View interactive version

Go hexagonal architecture is an AI agent skill from the GitHub repository makifbaysal/tasktrooper. Use when adding a use case, port, repository or adapter in a Go service — where each piece goes, how errors and transactions cross layers, and how to check the import direction

How to use this skill

Skill file

Hexagonal Architecture in Go

Detect the repo's layout first

get_repo_tree   # look for domain/port/application/adapter-named folders

Follow the repository's own names for these folders (internal/core, internal/service, whatever it already uses) — don't rename them to match this skill. Never restructure a repository that is not hexagonal in a feature task. If the repo has no layering at all, follow its existing flat/package-by-feature style instead of introducing hexagonal boundaries unasked.

Layers

Rules

Worked Example: "Archive a project"

  1. Domain errors: domain.ErrNotFound, domain.ErrConflict (sentinel errors the adapters translate into and the handler's central mapper translates out of).
  2. Port: port.ProjectStore with Archive(ctx context.Context, id uuid.UUID) error.
  3. Service + test: the use case calls the port; the test uses the port's mock/fake — no database in this test.
  4. Postgres adapter: translates driver errors into domain errors — errors.Is(err, pgx.ErrNoRows) → domain.ErrNotFound; pgErr.Code == "23505" → domain.ErrConflict. This translation happens in the adapter, never in the handler or service.
  5. Compile-time check: var _ port.ProjectStore = (*PGProjectStore)(nil) beside the constructor.
  6. Handler: maps through the one central error handler (fiber-rest-api) — no case-by-case mapping here.

Transactions across ports

Model the transaction boundary as a port, not a leaked *sql.Tx/pgx.Tx: port.TxRunner with WithinTx(ctx context.Context, fn func(ctx context.Context) error) error. The Postgres adapter puts the pgx.Tx into the returned ctx; repository adapters use the tx-in-context when present, falling back to the pool otherwise. The transaction boundary belongs to the use case (application layer), which decides what must commit together — never to a repository method.

Wiring

Constructors are called from main/a wiring package only — no package-level mutable globals holding dependencies (Uber "Avoid Global State").

Verify the import direction

go list -deps ./internal/domain/... ./internal/application/... | grep -E '/internal/adapter|gofiber|jackc/pgx|database/sql'

Adjust the paths to the repo's actual package names. Must print nothing — any hit is a boundary violation.

Smell Checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.