Go Clean Architecture API 鷹架

package: go-clean-api-scaffold
created_at: 2026/04/29 00:00:00
link: https://github.com/LaiJunBin/go-clean-api-scaffold

cover image

一個以 Clean Architecture 為基礎的 Go API 鷹架,結構、接線與測試的基礎建設都先準備好了。

clone 下來、用 OpenAPI 定義好 API,就可以直接開始寫 domain 的邏輯。

適合當地基

這個鷹架很適合讓 AI Agent 繼續在上面蓋房子。

AI 很會照著既有的樣子往下寫,所以地基長什麼樣子,蓋出來的房子大概就長什麼樣子:分層放哪裡、相依的方向、API 怎麼定義、測試怎麼寫,這些事情如果一開始就定好,Agent 就會跟著做,不用每次都在 prompt 裡重講一遍,也比較不會越蓋越歪。

我近期幾個 Go 的專案都是從這裡長出來的。

內建了什麼

  • 以目錄結構強制分層的 Clean Architecture
  • Contract-first:由 OpenAPI 3.0 產生 server 介面,規格裡有的端點沒實作就編譯不過
  • 以 Uber FX 做相依注入
  • BDD 整合測試(godog)與自動產生 mock 的單元測試(mockery)
  • 支援 Up / Down 的 migration
  • Hot reload(Air)、Docker Compose、Dev Container

結構

internal/app/hello_domain/hello/
├── domain/
│   ├── entity/           # 核心的商業邏輯
│   └── repository/       # Repository 介面
├── application/
│   └── usecase/          # 編排 domain 邏輯
├── adapter/
│   ├── controller/       # 接 HTTP 請求,呼叫 use case
│   └── presenter/        # 把輸出轉成 HTTP 回應
├── infrastructure/
│   └── repository/       # Repository 實作
└── provider.go           # 這個 bounded context 的 DI 綁定

相依方向:adapter -> application -> domain <- infrastructure

domain 層不相依任何框架或資料庫。

使用

$ cp config.example.yaml config.yaml
$ make migrate
$ make dev

hello_domain 是示範用的,準備好開始寫自己的專案時把它刪掉就可以了。