- Home
- Skills
- APIs & Backend
- Go Clean Architecture for Fiber + sqlc + pgx
Works with the AI Agents you already use
Go Clean Architecture for Fiber + sqlc + pgx
The result compiles, then becomes impossible to change.
$12
Go Clean Architecture for Fiber + sqlc + pgx
Example session with this skill installed
Add an orders feature to my Go API. A customer places an order with one or more line items (product SKU, quantity, unit price in cents); the order stores its total. I need POST /api/v1/orders and GET /api/v1/orders/:id, stored in Postgres with sqlc. Follow the same layers the customers feature uses.
- Read your context and instructions
- Compiled the go clean architecture
Orders feature added
POST /api/v1/orders and GET /api/v1/orders/:id are working. The build, vet and all tests pass. The Postgres side has not been run against a real database, because none is available here. sqlc checked the SQL against the migrations, but the transaction, the bulk insert and the foreign-key handling have not been executed.
// POST /api/v1/orders → 201
{"customer_id":"<uuid>","items":[{"sku":"SKU-1","quantity":2,"unit_price_cents":1250}]}
// response (GET /api/v1/orders/:id returns the same shape, 200)
{"id":"<uuid>","customer_id":"<uuid>","items":[{"sku":"SKU-1","quantity":2,"unit_price_cents":1250}],"total_cents":2500,"created_at":"..."}
How it behaves
Total: the server always works out the total (quantity × unit price, summed over the items) and stores it. The client never sends a total. If the total is too large to fit in a 64-bit number, the order is rejected rather than silently wrapping around to a wrong amount.
Saving: the order and its items are written in one transaction, so an order can never exist without its items. Items keep the order they were sent in.
- Errors, using your existing error format:
| Problem | Status | Code |
|---|---|---|
| Malformed JSON, or a fractional quantity | 400 | REQUEST_ERROR |
No items, empty SKU, quantity below 1, negative price, total too large, or customer_id not a UUID | 400 | VALIDATION_ERROR |
customer_id is not an existing customer | 400 | VALIDATION_ERROR |
| Order ID not found | 404 | NOT_FOUND |
Validation messages say which item failed, for example items[1]: invalid field "quantity".
Files
Created
migration/000002_create_orders.up.sql,migration/000002_create_orders.down.sql:ordersandorder_itemstables, with checks on quantity and prices.db/queries/orders.sql:CreateOrder,CreateOrderItems(bulk insert),GetOrder,ListOrderItems.internal/infra/postgres/gen/orders.sql.go,internal/infra/postgres/gen/copyfrom.go: generated bysqlc generate.internal/domain/valueobject/order_id.go,internal/domain/valueobject/sku.gointernal/domain/entity/order.go: the order and its line items, including the total calculation.internal/domain/repository/order_repository.gointernal/usecase/order/create_order.go,get_order.go,output.gointernal/infra/postgres/order_repository.gointernal/handler/order/handler.go- Tests:
internal/domain/entity/order_test.go,internal/usecase/order/create_order_test.go,internal/usecase/order/get_order_test.go,internal/handler/order/handler_test.go. The handler tests run real requests through the app, with an in-memory repository behind the real usecases.
Changed
cmd/api/main.go: wires the order repository, usecases and handler.internal/infra/postgres/gen/db.go,internal/infra/postgres/gen/models.go: regenerated by sqlc, not edited by hand.
Same layers as customers
I followed the customers feature's conventions even where the skill's naming table differs:
- the handler lives at
internal/handler/order/rather thaninternal/handler/router/{surface}/; - types are named
CreateOrderandHandler, notCreateOrderUsecaseandOrderHandler; Executereturns a value, not a pointer;- database errors are converted with your existing
mapPgError(err), which has no operation-name argument.
So the skill's "names match the style guide" check is deliberately not met; the code matches your codebase instead.
There is one difference from customers on purpose: SKUs read back from the database are not re-validated. Customers re-check stored emails, which means a bad stored value would come back as a 400 on a GET instead of a 500.
Verification (run here)
$ sqlc generate && sqlc vet && sqlc compile
exit 0
$ go build ./...
exit 0
$ go vet ./...
exit 0
$ go test -race -count=1 ./...
? github.com/acme/shopapi/cmd/api [no test files]
? github.com/acme/shopapi/internal/domain [no test files]
ok github.com/acme/shopapi/internal/domain/entity 1.630s
? github.com/acme/shopapi/internal/domain/repository [no test files]
? github.com/acme/shopapi/internal/domain/valueobject [no test files]
? github.com/acme/shopapi/internal/handler/apierror [no test files]
? github.com/acme/shopapi/internal/handler/customer [no test files]
ok github.com/acme/shopapi/internal/handler/order 2.681s
? github.com/acme/shopapi/internal/infra/postgres [no test files]
? github.com/acme/shopapi/internal/infra/postgres/gen [no test files]
? github.com/acme/shopapi/internal/usecase [no test files]
ok github.com/acme/shopapi/internal/usecase/customer 1.991s
ok github.com/acme/shopapi/internal/usecase/order 1.503s
exit 0
$ gofmt -l .
exit 0
sqlc vethas no rules configured insqlc.yaml, so it only confirms the queries parse.sqlc compileandgenerateare what checked the SQL against the schema.- To check the tests can fail, I temporarily broke the total calculation and the unknown-customer handling. The entity, usecase and handler tests all failed, and they passed again once I put the code back.
- Import checks found no Fiber or pgx imports in the domain or usecase packages, no domain or infra imports in non-test handler code, the generated sqlc code used only inside
internal/infra/postgres, and no logging in infra. Both repositories have a compile-time interface check.
Not verified
Database: there is no PostgreSQL or Docker here, so the migration was never applied. The repository's transaction, bulk insert, row mapping and foreign-key handling have not run against a real database. Please check them against your dev database before relying on them.
- Lint:
golangci-lintwas not run. The repo has no config for it, and it isn't installed here. - Commit: nothing is committed, including the regenerated sqlc code.
Questions for you
Unit prices: the client sends the unit price, as you described, and the server trusts it because there is no product catalog. Is that intended?
2.
Number of items: there is no limit on items per order. Fiber's default 4 MB body limit is the only cap. Should there be a limit?
3. Unknown customer: this returns 400 VALIDATION_ERROR. Would you rather have 404 or 422?
Spotted in existing code, not changed:
customerFromRowre-validates stored emails, so bad stored data shows up as a 400.main.gosets no read or write timeouts, and Fiber's read timeout has no limit by default.main.goshuts down through a goroutine callingapp.Shutdown()rather than Fiber v3'sListenConfig{GracefulContext: ...}.
Connects securely to your tools. The creator never sees your data.
About this skill
The problem
Agents writing Go backends tend to put SQL in handlers, leak sqlc row types into business logic, log the same error three times, and match on database errors in HTTP code. The result compiles, then becomes impossible to change.
What it does
- Scaffolds a feature across domain, usecase, infra and handler layers, with the dependency direction enforced.
- Keeps the domain framework-free: no Fiber, pgx, sqlc-generated types or DTOs.
- Implements repositories with sqlc + pgx, centralized error mapping, and a compile-time interface check on every implementation.
- Defines the error flow
domain | repository | service error → usecase error → API error, using%w,errors.Isanderrors.As, with the usecase owning error policy. - Logs each error once, at the edge.
- Passes
context.Contextfrom the Fiber request down to pgx so cancellation propagates. - Gives every goroutine an owner with a stop signal (no fire-and-forget).
- Flags the fasthttp buffer-reuse trap: values from
c.Params(),c.Query()andc.Body()must be copied before they outlive the handler. - Refactors mixed handler/business/IO code into layers, adds route groups, and adds background workers.
What's inside
SKILL.md: core rules, workflow and definition of done- 4 workflows: scaffold feature, add router domain, refactor to layers, add background task
- 10 references: architecture and layout, coding style, error handling, sqlc/pgx repositories, DB tool choice (why sqlc + pgx over GORM, ent, Bun and sqlx), distilled uber-go style, Go idioms, testing, linting, documentation
- 10 templates: entity, value object, repository interface, Postgres repository, usecase, Fiber handler, error types, background job, sqlc query file,
sqlc.yaml
Frameworks & tools
Go, Fiber v3, sqlc, pgx/v5, PostgreSQL, golang-migrate, golangci-lint.
Why this beats prompting it yourself
Every rule is written down and checked: which package may import what, where DTOs and generated types stop, which layer logs, and what "done" means (go build, go vet and go test -race all pass, plus golangci-lint and sqlc generate when they apply). The templates show the exact shape for each layer instead of leaving the agent to invent one.
Use cases
- Starting a new Go API with a layout that will survive its tenth feature.
- Adding a feature to an existing Fiber + sqlc codebase without breaking layer boundaries.
- Refactoring a handler that talks to the database directly.
- Designing consistent API error responses.
- Adding a background worker with a clean shutdown.
Known limitations
Opinionated toward Fiber v3 + sqlc + pgx + PostgreSQL. Other routers or ORMs need adaptation. It does not drive a TDD loop, set up CI/CD, or profile performance.
Opinionated toward Fiber v3 + sqlc + pgx + PostgreSQL; other routers or ORMs need adaptation. It does not drive a TDD loop, define a full test strategy, set up CI/CD, or profile performance. Repository changes still need verifying against a real database.
How to use
- 1
Connect your agent to the Agensi MCP
Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup
- 2
Sign in to Agensi
Your agent shows a sign-in link. Sign in and click Allow.
- 3
Ask for what you need
Your agent loads this skill and uses it on your task. It always asks before any payment.
Reviews
No reviews yet
Be one of the first to try it. Every listed skill goes through the trust checks below.
Security scanned
Checked by our 8-point scan before listing
Fresh listing
Recently published to Agensi
Money-back guarantee
Doesn't do what its page promises? You get your money back.
Trust & safety
Security scan
Security scan passed 8 days ago
Requires
Permissions
File Scopes
Shell runs go build, go vet, go test -race and sqlc generate in your project. Read and Write are used to create and edit Go, SQL and sqlc config files. The skill ships no scripts and makes no network calls.