前面幾篇談了踩坑經驗與心法,這篇用一個完整的 Go 後端工作流示範案例把它們串起來。

技術堆疊選的是 Go 1.22 + Gin + PostgreSQL + GORM,目標是把一個 IoT 裝置管理後端的首輪核心骨架跑通:分層目錄、資料模型、Device CRUD API、JWT 與日誌中介軟體以及本機整合測試(即時推播、告警規則引擎等複雜業務留待後續迭代,不混在首輪初始骨架裡)。下面按步驟拆解:每一步怎麼給 Prompt、貼出關鍵程式碼、哪些地方容易踩坑需要人工介入,以及哪些環節 Claude 幫不上忙。


第 0 步:撰寫 CLAUDE.md

開始寫任何程式碼之前,我先讓 Claude 幫我產生一份 CLAUDE.md 初稿,再手動調整。

反面 CLAUDE.md(太籠統,Claude 會反覆追問你):

1
2
# 專案
Go 後端專案,程式碼寫好一點。

正面 CLAUDE.md(具體、可執行):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 專案資訊
- 語言: Go 1.22
- 框架: Gin
- 資料庫: PostgreSQL (GORM)
- 專案結構: 依 handler / service / repository / model 分層

# 程式碼規範
- 錯誤處理: 使用 internal/errors 套件的自訂錯誤型別
- 日誌: 使用 internal/logger,不直接用 fmt.Println
- 命名: Go 標準命名規範,handler 用 XxxHandler,service 用 XxxService

# 注意事項
- 所有 API 必須經過 auth 中介軟體
- 資料庫操作透過 repository 層,handler 不直接呼叫 GORM
- 設定項目從環境變數讀取,不硬編碼

差別在於:泛泛的「寫好程式碼」沒用,具體的「所有 API 必須經過 auth 中介軟體」才能約束 Claude 的行為。這份 CLAUDE.md 花了我 10 分鐘,但後續每一步都省下了反覆溝通的時間。


第 1 步:專案骨架

我的 prompt:

初始化一個 Go 後端專案,使用 Gin 框架。按 handler / service / repository / model 分層。建立 main.go 進入點與基本的目錄結構。

Claude 產生了完整的目錄結構與設定檔:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
l4_cloud/
├── cmd/server/main.go
├── internal/
│ ├── handler/
│ ├── service/
│ ├── repository/
│ ├── model/
│ ├── middleware/
│ └── errors/
├── config/
│ └── config.go
├── Makefile
├── go.mod
└── .env.example

Makefile 也一併產生:

1
2
3
4
5
6
7
8
9
10
11
12
13
.PHONY: build run test clean

build:
go build -o bin/server ./cmd/server

run:
go run ./cmd/server

test:
go test ./... -v

clean:
rm -rf bin/

我做的調整:保留標準 Go 目錄佈局 cmd/server/main.go(與上面的 Makefile 保持一致),順手補齊了 .env.example 裡缺少的資料庫連線字串與 JWT_SECRET 預留項目。

耗時:5 分鐘(純手寫至少 30 分鐘)


第 2 步:資料模型

我的 prompt:

定義以下資料模型:Device(裝置,包含 name、type、status 欄位)、SensorData(感測器資料,包含 device_id、temperature、humidity、timestamp)。用 GORM 的標準寫法,參考 CLAUDE.md 裡的分層結構。

調整後的 Device 模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// internal/model/device.go
package model

import "gorm.io/gorm"

type DeviceStatus string

const (
DeviceStatusOnline DeviceStatus = "online"
DeviceStatusOffline DeviceStatus = "offline"
DeviceStatusAlarm DeviceStatus = "alarm"
)

func (s DeviceStatus) IsValid() bool {
switch s {
case DeviceStatusOnline, DeviceStatusOffline, DeviceStatusAlarm:
return true
default:
return false
}
}

type Device struct {
gorm.Model
Name string `json:"name" gorm:"not null"`
Type string `json:"type" gorm:"not null"`
Status DeviceStatus `json:"status" gorm:"type:varchar(20);default:'offline'"`
}

踩坑 1:Status 欄位型別。Claude 一開始直接把 Status 寫成原始的 string,雖然能跑但沒有型別約束。我改成了自訂列舉型別 DeviceStatus 並補上 IsValid(),在 service 層驗證狀態值,防止寫入任意字串。

踩坑 2:SensorData 的 timestamp 重複。gorm.Model 內建 CreatedAt,而 SensorData 在業務上需要一個獨立的採集時間戳記。Claude 自動加的 Timestamp 欄位跟 CreatedAt 語意重疊,我移除了 Timestamp,改用 gorm.Model 內建的時間欄位:

1
2
3
4
5
6
7
8
9
10
11
// internal/model/sensor_data.go
package model

import "gorm.io/gorm"

type SensorData struct {
gorm.Model
DeviceID uint `json:"device_id" gorm:"index;not null"`
Temperature float64 `json:"temperature"`
Humidity float64 `json:"humidity"`
}

耗時:10 分鐘(含調整)


第 3 步:CRUD API

我的 prompt:

為 Device 模型實作完整的 CRUD API。要求:

  1. 遵循 handler / service / repository 分層
  2. 使用 Gin 的路由群組,加上 auth 中介軟體(先用佔位中介軟體)
  3. 錯誤回傳採用統一格式 { "code": 40001, "message": "xxx" }
  4. 撰寫單元測試,mock repository 層

這一步 Claude 產生了約 400 行程式碼,分層清晰。關鍵片段:

Handler 層(列表 API):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// internal/handler/device.go
func (h *DeviceHandler) List(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

devices, total, err := h.service.List(page, pageSize)
if err != nil {
errors.Respond(c, errors.ErrInternal)
return
}

c.JSON(http.StatusOK, gin.H{
"data": devices,
"total": total,
"page": page,
})
}

統一錯誤格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// internal/errors/errors.go
package errors

import (
"net/http"

"github.com/gin-gonic/gin"
)

type AppError struct {
HTTPStatus int `json:"-"`
Code int `json:"code"`
Message string `json:"message"`
}

func Respond(c *gin.Context, err *AppError) {
status := err.HTTPStatus
if status == 0 {
status = http.StatusInternalServerError
}
c.JSON(status, err)
}

var (
ErrBadRequest = &AppError{HTTPStatus: http.StatusBadRequest, Code: 40001, Message: "請求參數錯誤"}
ErrNotFound = &AppError{HTTPStatus: http.StatusNotFound, Code: 40401, Message: "資源不存在"}
ErrInternal = &AppError{HTTPStatus: http.StatusInternalServerError, Code: 50001, Message: "服務內部錯誤"}
)

改動 1:HTTP 狀態碼不能寫死 400。初版 Respond() 直接硬編碼了 http.StatusBadRequest,導致 ErrNotFound 與 ErrInternal 也會回傳 HTTP 400。幫 AppError 加上不參與 JSON 序列化的 HTTPStatus 欄位後,業務錯誤碼與 HTTP 狀態碼才能一一對應。

改動 2:分頁預設值與邊界檢查。Claude 產生的 page 預設值是 0,但頁碼從 0 開始違反直覺,而且傳入負數時會直接帶入資料庫查詢,改成預設 1 並加上邊界保護:

1
2
3
4
5
6
7
8
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 100 {
pageSize = 20
}

測試程式碼(mock repository,注意分頁越界保護,避免 start > len(m.devices) 觸發 slice panic):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// internal/handler/device_test.go
type mockRepo struct {
devices []model.Device
}

func (m *mockRepo) List(page, pageSize int) ([]model.Device, int64, error) {
total := int64(len(m.devices))
start := (page - 1) * pageSize
if start < 0 {
start = 0
}
if start >= len(m.devices) {
return []model.Device{}, total, nil
}
end := start + pageSize
if end > len(m.devices) {
end = len(m.devices)
}
return m.devices[start:end], total, nil
}

耗時:15 分鐘(純手寫至少 2 小時)


第 4 步:中介軟體

我的 prompt:

寫兩個中介軟體:

  1. auth 中介軟體:從 Header 擷取 Bearer token,驗證 JWT,把使用者資訊注入 context
  2. 日誌中介軟體:記錄每個請求的方法、路徑、耗時、狀態碼
    參考現有程式碼風格。

Claude 產生的 auth 中介軟體:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// internal/middleware/auth.go
func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": 40101,
"message": "缺少認證資訊",
})
return
}

tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
claims, err := parseToken(tokenStr, jwtSecret)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": 40101,
"message": "token 無效或已過期",
})
return
}

c.Set("userID", claims.UserID)
c.Next()
}
}

踩坑:金鑰硬編碼。Claude 最初把 jwtSecret 當成常數寫在檔案裡。我改成從設定檔注入(函式參數),設定檔再從環境變數讀取:

1
2
3
4
5
6
7
// config/config.go
type Config struct {
JWTSecret string `env:"JWT_SECRET" required:"true"`
DBHost string `env:"DB_HOST" default:"localhost"`
DBPort string `env:"DB_PORT" default:"5432"`
DBName string `env:"DB_NAME" default:"l4_cloud"`
}

日誌中介軟體沒什麼坑,Claude 直接使用了專案既有的 internal/logger,輸出格式統一:

1
2
3
4
5
6
7
8
9
10
11
12
13
// internal/middleware/logger.go
func LoggerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
logger.Info("%s %s %d %v",
c.Request.Method,
c.Request.URL.Path,
c.Writer.Status(),
time.Since(start),
)
}
}

耗時:10 分鐘


第 5 步:整合測試

這一步 Claude 能幫的忙有限,因為需要實際運作的服務與資料庫。

啟動 PostgreSQL:

1
2
3
4
5
docker run -d --name l4-postgres \
-e POSTGRES_PASSWORD=secret \
-e POSTGRES_DB=l4_cloud \
-p 5432:5432 \
postgres:16

執行測試:

1
2
3
4
5
6
make test
# === RUN TestListDevices
# --- PASS: TestListDevices (0.00s)
# === RUN TestCreateDevice
# --- PASS: TestCreateDevice (0.00s)
# ok l4_cloud/internal/handler 0.012s

curl 測試:

1
2
3
4
5
6
7
8
9
# 建立裝置
curl -X POST http://localhost:8080/api/v1/devices \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"name":"sensor-01","type":"temperature"}'

# 查詢裝置清單
curl http://localhost:8080/api/v1/devices?page=1&page_size=10 \
-H "Authorization: Bearer <token>"

踩坑:JSON tag 拼字錯誤。初版整合測試時 API 回傳了 {"devie_id": 1} 而不是 device_id,原因是最初產生的 SensorData 結構體 JSON tag 寫成了 `json:"devie_id"`(上面第 2 步貼的是修復後的版本)。這類 typo 用肉眼很容易漏看,curl 跑一遍立刻現形。

踩坑:空紀錄與資料庫錯誤混為一談。查詢單一裝置時,如果把所有 err != nil 全部回傳 404,會掩蓋真正的資料庫連線故障;而如果 repository 某些分支回傳 (nil, nil),直接序列化也會出問題。改成明確區分 gorm.ErrRecordNotFound 與內部錯誤,並加上 device == nil 的防呆檢查:

1
2
3
4
5
6
7
8
9
10
11
12
13
device, err := h.service.GetByID(id)
if err != nil {
if stderrors.Is(err, gorm.ErrRecordNotFound) {
errors.Respond(c, errors.ErrNotFound)
return
}
errors.Respond(c, errors.ErrInternal)
return
}
if device == nil {
errors.Respond(c, errors.ErrNotFound)
return
}

耗時:30 分鐘


時間對比

環節 純手寫預估時間 用 Claude Code 節省
專案骨架 30 min 5 min 83%
資料模型 20 min 10 min 50%
CRUD API 2 h 15 min 87%
中介軟體 1 h 10 min 83%
整合測試 1 h 30 min 50%
總計 ~5 h ~1 h 10 min ~76%

最大的效率提升在 CRUD API——這類有固定模式、分層清晰的程式碼,Claude 幾乎可以一次寫對。資料模型與整合測試環節節省比例最低,因為需要你做業務判斷與實際驗證。


什麼環節 Claude 幫不上忙

老實說,以下環節我基本上都是自己來。我總結了一個簡單的判斷框架:

Claude 能幫的(模式明確、可從 CLAUDE.md 推斷):

  • 有固定模式的程式碼(CRUD、中介軟體、設定載入)
  • 專案骨架與目錄結構
  • 單元測試與 mock 程式碼
  • 已知 bug 的修復(把錯誤訊息貼給它就行)

Claude 幫不上的(需要業務上下文或環境驗證):

環節 為什麼幫不上 你的對策
架構設計 選型取決於業務規模、團隊能力、維運條件 自己做決策,讓 Claude 幫你實作
業務門檻值 「離線多久算異常」它不知道 你定義規則,讓 Claude 寫判斷邏輯
部署設定 Docker Compose、Nginx 設定需要實際環境驗證 自己寫與除錯
程式碼架構審查 「這個 service 承擔了太多職責」屬於主觀判斷 自己 review,Claude 發現不了

簡單判斷標準:如果你的決策需要知道「公司有多少裝置」、「QPS 大概多少」、「團隊誰負責什麼」,那 Claude 幫不上。如果你的決策只需要知道「用什麼框架」、「程式碼怎麼分層」、「命名規範是什麼」,那 CLAUDE.md 寫好就夠了。


關鍵經驗

1. CLAUDE.md 是投資報酬率最高的 10 分鐘。 寫得越具體,後續每個環節的溝通成本越低。「程式碼寫好一點」是廢話,「handler 不直接呼叫 GORM」才是有效指令。

2. 分層架構天生適合 AI 輔助。 每層職責清晰,prompt 也好寫——「幫 model 層加一個欄位」、「在 handler 裡處理分頁」。如果專案是義大利麵程式碼,Claude 也無從下手。

3. 審查重點放在業務邏輯,語法層面基本可以信任。 Claude 產生的程式碼語法錯誤極少,但業務邊界(分頁從 0 還是 1 開始、空指標怎麼處理)需要你把關。養成「先讓它寫,再跑一遍 curl」的習慣。


系列導覽