Vibe Coding
開發架構生產級87% · 高可完成

Go Gin 微服務與 sqlc 類型安全資料層 Vibe Coding 規範配置

透過 .cursor/rules 與 sqlc.yaml 實現 87% 自動化,確保 API 校驗、SQL 類型安全與 OTel 鏈路追蹤的無縫整合。

預計耗時: 75 min更新: 2026-11-27
Cursor IDEGo 1.23GinsqlcOpenTelemetry
Go Gin 微服務與 sqlc 類型安全資料層 Vibe Coding 規範配置

量化可完成度

87% 的完成度表明 AI 在生成標準 HTTP Handler、sqlc 查詢綁定及基礎 OTel 整合方面表現卓越,能自動處理大部分樣板程式碼。剩餘 13% 主要涉及複雜併發競態處理、優雅停機邏輯及特定業務邊界條件的微調,需人工深度介入。

87%高可完成

四維達成明細

Gin 路由與參數校驗綁定92%

AI 能準確生成帶有 validator 標籤的結構體及標準回應格式,但需人工確認邊界條件如空指標處理。

sqlc 編譯期 SQL 類型安全94%

sqlc 生成程式碼類型安全極高,AI 能正確呼叫生成方法,僅需注意複雜 JSONB 解析的邊界情況。

OpenTelemetry 上下文透傳84%

AI 能正確注入 span,但在跨服務呼叫或異步 goroutine 中的 context 傳遞易出錯,需人工檢查。

併發競態與優雅停機78%

AI 生成的併發程式碼可能存在競態條件,優雅停機邏輯需人工驗證超時設定與資源釋放順序。

人工把關檢查點

在部署前,必須人工審查所有涉及資料庫事務的程式碼區塊,確保事務邊界正確且無死鎖風險。同時,需驗證 OpenTelemetry 的 trace_id 在日誌與追蹤系統中的一致性,確保鏈路追蹤無斷點。

升級 / 降級路徑

若資源受限,可暫時禁用 OpenTelemetry 的採樣率至 10% 以降低開銷,或簡化 sqlc 的自訂類型映射以加快生成速度。若需更高效能,可引入連接池最佳化配置或啟用 Go 的 PGO(Profile-Guided Optimization)進行編譯最佳化。

適用場景與前提

適用於使用 Go 1.23 和 Gin 架構建構微服務的開發團隊,特別是需要處理複雜 SQL 查詢並整合 OpenTelemetry 追蹤的場景。前提環境需安裝 Go 1.23+、sqlc CLI 及 PostgreSQL 資料庫。理想用例包括高併發 API 網關、訂單處理系統及需要嚴格資料一致性的金融類應用。

可直接複製的工程設定

.cursor/rules/go-gin-sqlc.mdcmarkdown

定义 Go Gin 与 sqlc 的 AI 代码生成规范,强制类型安全与 OTel 集成。

---
alwaysApply: true
---
# Go Gin & sqlc Vibe Coding Rules

## 1. API Handlers (Gin)
- **Binding**: Always use `ShouldBindJSON` or `ShouldBindQuery` with explicit struct tags.
- **Validation**: Use `go-playground/validator` tags on request structs.
- **Response**: Standardize response format: `{ "code": int, "msg": string, "data": any }`.
- **Error Handling**: Never return raw errors to client. Use `c.JSON(http.StatusInternalServerError, ...)` with sanitized messages.

## 2. Data Layer (sqlc)
- **No Raw SQL**: Do not write raw SQL strings in Go code. Always use `sqlc` generated methods.
- **Context**: Pass `context.Context` as the first argument to all DB queries.
- **Transactions**: Use `sqlc` generated `Tx` methods for multi-step writes.

## 3. Observability (OpenTelemetry)
- **Tracing**: Inject `otel` span at the start of every Handler.
- **Logging**: Use `slog` (Go 1.21+) with structured fields. Include `trace_id` and `span_id` in log attributes.
- **Middleware**: Ensure `otelgin` middleware is applied globally.

## 4. Concurrency & Safety
- **Goroutines**: Always use `context` for cancellation. Avoid `time.Sleep` in critical paths.
- **Graceful Shutdown**: Implement `http.Server.Shutdown` with a timeout.
- **Race Conditions**: Use `sync.Mutex` or channels for shared state. Run `go test -race` locally.
sqlc.yamlyaml

配置 sqlc 代码生成器,指定 Go 输出路径与类型映射。

version: "2"
sql:
  - engine: "postgresql"
    schema: "./migrations"
    queries: "./queries"
    gen:
      go:
        package: "db"
        out: "./internal/db"
        emit_interface: true
        emit_prepared_queries: false
        emit_empty_slices: true
        overrides:
          - db_type: "timestamptz"
            go_type: "time.Time"
          - db_type: "uuid"
            go_type: "github.com/google/uuid.UUID"
          - db_type: "jsonb"
            go_type: "json.RawMessage"
          - db_type: "int8"
            go_type: "int64"
          - db_type: "float8"
            go_type: "float64"
          - db_type: "bool"
            go_type: "bool"
          - db_type: "text"
            go_type: "string"
          - db_type: "varchar"
            go_type: "string"
          - db_type: "bytea"
            go_type: "[]byte"
          - db_type: "inet"
            go_type: "net.IP"
          - db_type: "cidr"
            go_type: "net.IPNet"
          - db_type: "macaddr"
            go_type: "net.HardwareAddr"
          - db_type: "macaddr8"
            go_type: "net.HardwareAddr"
          - db_type: "inet"
            go_type: "net.IP"
          - db_type: "cidr"
            go_type: "net.IPNet"
          - db_type: "macaddr"
            go_type: "net.HardwareAddr"
          - db_type: "macaddr8"
            go_type: "net.HardwareAddr"

AI Vibe Coding 四步實戰

完成進度: 0 / 4
  1. 1

    初始化專案結構與 sqlc 配置

    目標: 建立 Go 模組結構,配置 sqlc.yaml 並生成初始資料庫程式碼。

    Prompt
    請初始化一個 Go 1.23 專案,使用 Gin 框架。建立 internal/db 目錄,並配置 sqlc.yaml 以支援 PostgreSQL。生成一個範例查詢:取得使用者 ID 為 1 的使用者資訊。確保 sqlc 生成的程式碼類型安全,並處理 UUID 和 time.Time 類型。

    驗收標準: 執行 `sqlc generate` 無錯誤,且 `go build ./...` 成功編譯。檢查 internal/db 目錄下生成的程式碼是否包含正確的類型定義。

  2. 2

    實現 Gin Handler 與參數校驗

    目標: 建立 HTTP Handler,綁定請求參數並執行資料庫查詢。

    Prompt
    建立一個 GET /users/:id 介面。使用 Gin 綁定路徑參數,並呼叫 sqlc 生成的 GetUser 方法。返回標準 JSON 格式 {code, msg, data}。若使用者不存在,返回 404 狀態碼。確保使用 context.Context 傳遞請求上下文。

    驗收標準: 使用 curl 測試介面:`curl -H 'Accept: application/json' http://localhost:8080/users/1`。驗證返回 JSON 格式正確,且 404 情況處理得當。

  3. 3

    整合 OpenTelemetry 與結構化日誌

    目標: 新增 OTel 中間件和 slog 日誌,確保 trace_id 透傳。

    Prompt
    在 Gin 引擎中加入 otelgin 中間件。使用 slog 記錄請求日誌,包含 trace_id 和 span_id。確保在 Handler 中建立 span,並在日誌中輸出 span 資訊。驗證日誌格式為 JSON,且包含必要的追蹤欄位。

    驗收標準: 啟動服務並發送請求,檢查日誌輸出是否包含 trace_id。使用 Jaeger 或 Zipkin 驗證 trace 鏈路是否完整,無斷點。

  4. 4

    併發安全與優雅停機

    目標: 實現優雅停機邏輯,並確保併發安全。

    Prompt
    實現 http.Server 的優雅停機,設定 5 秒超時。確保在停機時關閉資料庫連接和 OTel 匯出器。新增一個併發測試用例,驗證在多個請求下無競態條件。使用 go test -race 驗證。

    驗收標準: 執行 `go test -race ./...` 無競態警告。發送 SIGTERM 訊號,驗證服務在 5 秒內優雅關閉,且日誌記錄關閉過程。

常見踩坑與解法

  • sqlc 生成程式碼未更新:修改 SQL 後忘記執行 `sqlc generate`,導致編譯錯誤。修復:將 `sqlc generate` 加入 pre-commit hook 或 Makefile。
  • OTel 上下文遺失:在 goroutine 中未傳遞 context,導致 trace 斷鏈。修復:始終使用 `ctx := context.WithValue(parentCtx, ...)` 傳遞上下文。
  • 併發競態:共用變數未加鎖,導致資料不一致。修復:使用 `sync.Mutex` 或 channel 保護共用狀態,並執行 `go test -race`。

常見問題

sqlc 生成的程式碼如何與 Gin 整合?

sqlc 生成的程式碼是純 Go 函數,可直接在 Gin Handler 中呼叫。只需確保傳入正確的 context.Context 和參數,並處理返回的 error。

如何驗證 OpenTelemetry 追蹤是否正常運作?

使用 Jaeger 或 Zipkin 等追蹤後端,發送請求後檢查 trace 鏈路是否完整。確保日誌中的 trace_id 與追蹤系統中的 ID 一致。

如何處理資料庫連接池配置?

使用 `sql.Open` 時設定 `SetMaxOpenConns` 和 `SetMaxIdleConns`。根據負載調整參數,避免連接耗盡。

相關方案

Go Gin 微服務與 sqlc 類型安全資料層 Vibe Coding 規範配置 · CursorHome