Go Gin Microservices and sqlc Type-Safe Data Layer Vibe Coding Specification
Achieve 87% automation through .cursor/rules and sqlc.yaml, ensuring seamless integration of API validation, SQL type safety, and OTel tracing.

Completion Score
The 87% completion rate indicates that AI excels at generating standard HTTP handlers, sqlc query bindings, and basic OTel integration, automatically handling most boilerplate code. The remaining 13% involves complex concurrency race handling, graceful shutdown logic, and fine-tuning specific business edge cases, requiring deep manual intervention.
Dimension breakdown
AI can accurately generate structs with validator tags and standard response formats, but manual confirmation is needed for edge cases such as nil pointer handling.
sqlc-generated code has extremely high type safety, and AI can correctly call the generated methods, though complex JSONB parsing edge cases should be noted.
AI can correctly inject spans, but context passing in cross-service calls or async goroutines is prone to errors and requires manual inspection.
AI-generated concurrent code may contain race conditions, and graceful shutdown logic requires manual verification of timeout settings and resource release order.
Human checkpoint
Before deployment, all code blocks involving database transactions must be manually reviewed to ensure correct transaction boundaries and no deadlock risk. Additionally, the consistency of OpenTelemetry trace_id across logs and tracing systems must be verified to ensure uninterrupted tracing.
Upgrade / downgrade path
If resources are constrained, OpenTelemetry sampling can be temporarily reduced to 10% to lower overhead, or sqlc custom type mappings can be simplified to speed up generation. For higher performance, connection pool optimization can be introduced or Go's PGO (Profile-Guided Optimization) can be enabled for compilation.
When to use & prerequisites
Suitable for development teams using Go 1.23 and the Gin framework to build microservices, especially those handling complex SQL queries and integrating OpenTelemetry tracing. Prerequisites include Go 1.23+, the sqlc CLI, and a PostgreSQL database. Ideal use cases include high-concurrency API gateways, order processing systems, and financial applications requiring strict data consistency.
Ready-to-copy configs
定义 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 代码生成器,指定 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 in 4 steps
- 1
Initialize Project Structure and sqlc Configuration
Goal: Set up the Go module structure, configure sqlc.yaml, and generate initial database code.
PromptInitialize a Go 1.23 project using the Gin framework. Create an internal/db directory and configure sqlc.yaml to support PostgreSQL. Generate an example query: fetch user information for user ID 1. Ensure the sqlc-generated code is type-safe and handles UUID and time.Time types.Verify:
Run `sqlc generate` without errors, and ensure `go build ./...` compiles successfully. Check that the code generated in the internal/db directory contains correct type definitions. - 2
Implement Gin Handler and Parameter Validation
Goal: Create an HTTP handler, bind request parameters, and execute database queries.
PromptCreate a GET /users/:id endpoint. Use Gin to bind path parameters and call the sqlc-generated GetUser method. Return a standard JSON format {code, msg, data}. If the user does not exist, return a 404 status code. Ensure context.Context is used to pass the request context.Verify:
Test the endpoint with curl: `curl -H 'Accept: application/json' http://localhost:8080/users/1`. Verify that the returned JSON format is correct and that the 404 case is handled properly. - 3
Integrate OpenTelemetry and Structured Logging
Goal: Add OTel middleware and slog logging to ensure trace_id propagation.
PromptAdd the otelgin middleware to the Gin engine. Use slog to log requests, including trace_id and span_id. Ensure spans are created in the handler and span information is output in the logs. Verify that the log format is JSON and includes the necessary tracing fields.Verify:
Start the service and send requests, then check whether the log output includes trace_id. Use Jaeger or Zipkin to verify that the trace chain is complete with no gaps. - 4
Concurrency Safety and Graceful Shutdown
Goal: Implement graceful shutdown logic and ensure concurrency safety.
PromptImplement graceful shutdown for http.Server with a 5-second timeout. Ensure database connections and the OTel exporter are closed during shutdown. Add a concurrency test case to verify no race conditions under multiple requests. Use go test -race to verify.Verify:
Run `go test -race ./...` with no race warnings. Send a SIGTERM signal and verify that the service shuts down gracefully within 5 seconds, with shutdown process logged.
Pitfalls & fixes
- sqlc generated code not updated: SQL is modified but `sqlc generate` is not run, causing compilation errors. Fix: Add `sqlc generate` to a pre-commit hook or Makefile.
- OTel context loss: context is not passed in a goroutine, causing trace disconnection. Fix: Always use `ctx := context.WithValue(parentCtx, ...)` to pass context.
- Concurrency race: shared variables are not locked, causing data inconsistency. Fix: Use `sync.Mutex` or channels to protect shared state, and run `go test -race`.
FAQ
How does sqlc-generated code integrate with Gin?
sqlc-generated code is pure Go functions that can be called directly in Gin handlers. Just ensure the correct context.Context and parameters are passed, and handle the returned error.
How do I verify that OpenTelemetry tracing is working correctly?
Use a tracing backend such as Jaeger or Zipkin, send a request, and check whether the trace chain is complete. Ensure that the trace_id in the logs matches the ID in the tracing system.
How do I handle database connection pool configuration?
When using `sql.Open`, set `SetMaxOpenConns` and `SetMaxIdleConns`. Adjust the parameters based on load to avoid connection exhaustion.


