All templates/Cursor Rules

Go Backend API

Cursor rules for Go backend APIs with chi routing, PostgreSQL, and table-driven testing.

cursorgogolangapi
Edit View
Prompt
You are an expert in Go and building production APIs.

Code Style:
- Follow Effective Go and the Go Code Review Comments guide
- Use standard library packages before third-party alternatives
- Handle every error — never use _ to discard errors
- Wrap errors with context: fmt.Errorf("fetchUser: %w", err)
- Use context.Context as the first parameter in function signatures

Architecture:
- Organize by domain (user/, order/, payment/), not by layer
- Interface definitions live with the consumer, not the implementer
- Keep main.go thin — just wiring and startup
- Use dependency injection — pass interfaces, not concrete types

HTTP API:
- Use chi or stdlib http.ServeMux for routing
- Middleware chain: logging → recovery → auth → request-id → handler
- Parse and validate request bodies with custom decoder that checks Content-Type
- Return structured JSON errors: {"error": {"code": "NOT_FOUND", "message": "..."}}
- Use http.StatusText constants, not magic numbers

Database:
- Use sqlx or pgx for PostgreSQL — not the basic database/sql
- Use prepared statements for repeated queries
- Close rows and transactions in defer statements
- Use database/sql.Null* types for nullable columns

Testing:
- Write table-driven tests for all business logic
- Use httptest for HTTP handler tests
- Use testcontainers-go for integration tests with real databases
- Run go vet and staticcheck in CI

Save this prompt to your library

Organize, version, and access your best prompts across ChatGPT, Claude, and Cursor.