CLAUDE.md rules for Go backends with Go 1.22+ routing, store interfaces, wrapped sentinel errors, errgroup concurrency and race-tested table tests.
.claude/rules/claude-go-backend-developer.md. Downloaded files need to be placed in that repository path.---
paths:
- "**/*"
---
# Go Backend Conventions
Applies to: Go HTTP APIs and backend services in this repository.
Version baseline: checked against Go 1.27 (1.26 also supported). Read `go.mod`. The `go` directive decides which language features and standard-library APIs you may use.
## Principles
- Prefer simple, explicit code: plain functions and structs over frameworks and deep abstractions.
- Handle every error where it is returned. Add context with `fmt.Errorf("doing X: %w", err)` and return it, or handle it fully. Never do both (log and return).
- Use composition: embed or hold small types instead of building hierarchies.
- Declare interfaces in the package that consumes them, keep them small, and return concrete types from constructors.
- Use goroutines and channels when they simplify the design, and give every goroutine a clear owner and stop condition.
## HTTP handlers
- Register routes with Go 1.22+ patterns: `mux.HandleFunc("GET /users/{id}", s.handleGetUser)`. Read wildcards with `r.PathValue`.
- Handlers depend on a service or store interface, not on `*sql.DB` directly. SQL lives in the store.
- Map domain errors to status codes in one place and never send internal error text to clients.
```go
type UserStore interface {
GetUser(ctx context.Context, id string) (User, error)
}
type Server struct {
users UserStore
logger *slog.Logger
}
func (s *Server) handleGetUser(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := r.PathValue("id")
user, err := s.users.GetUser(ctx, id)
if errors.Is(err, ErrNotFound) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "user not found"})
return
}
if err != nil {
s.logger.ErrorContext(ctx, "get user", "error", err, "id", id)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
return
}
writeJSON(w, http.StatusOK, user)
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v) // headers are sent; nothing useful to do on failure
}
```
## Errors
- Define sentinel errors for conditions callers branch on (`var ErrNotFound = errors.New("not found")`), and use custom error types when callers need fields.
- The store translates `sql.ErrNoRows` (or `pgx.ErrNoRows`) into `ErrNotFound`, so handlers never import driver packages.
- Check errors with `errors.Is`/`errors.As` (`errors.AsType[T]` on Go 1.26+), never with string comparison.
```go
func (s *Service) GetUser(ctx context.Context, id string) (User, error) {
u, err := s.store.GetUser(ctx, id)
if err != nil {
return User{}, fmt.Errorf("get user %s: %w", id, err)
}
return u, nil
}
```
## Concurrency
- Pass `ctx` as the first parameter and respect cancellation in loops and blocking calls.
- Use `errgroup.WithContext` for fan-out that must stop on the first error, and `g.SetLimit(n)` to bound parallelism.
- Since Go 1.22, loop variables are per-iteration, so don't add `item := item` copies.
```go
func ProcessItems(ctx context.Context, items []Item) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8)
for _, item := range items {
g.Go(func() error { return processItem(ctx, item) })
}
return g.Wait()
}
```
- Protect shared state with a mutex, or confine it to one goroutine. Run tests with `-race`.
## Tests
- Table-driven tests with `t.Run`. Use `httptest` for handlers and fakes of the small interfaces for stores.
## Verify before finishing
Run when available: `gofmt -l .` (no output), `go vet ./...`, `go test -race ./...`, and the repository's linter (`staticcheck` or `golangci-lint run`) if configured.
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.
Claude
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
Claude Code works in a Go HTTP API repository and this file is loaded as a project rule, for example .claude/rules/go-backend.md scoped to **/*.go.
Add GET /users/{id} returning JSON. internal/store/users.go currently returns sql.ErrNoRows for missing users and the handler compares err.Error() == "sql: no rows in result set". go.mod: go 1.26.Illustrative; not a recorded model run. The store maps sql.ErrNoRows to ErrNotFound; the service wraps with %w; the handler is registered as "GET /users/{id}", depends on a UserStore interface, branches with errors.Is, returns a JSON 404/500 without internal error text and logs with slog ErrorContext; the string comparison is removed; any fan-out uses errgroup with SetLimit and no loop-variable copies; a table-driven httptest test covers 200/404/500; the summary lists gofmt, go vet and go test -race output.Claude Code loads persistent project instructions from CLAUDE.md files and from Markdown rules in .claude/rules/. Rules can be scoped to file paths with a paths frontmatter field, and CLAUDE.md can import other files with @path syntax. The rules in this directory are written as plain instruction prompts: in Claude Code, save them as CLAUDE.md or .claude/rules/ content; in Claude.ai or the Claude API, use the same text as project instructions or a system prompt instead.
.claude/rules/claude-go-backend-developer.mdStarting point, not a tested configuration for your repository. Loaded when Claude Code works with files matching paths. Review the instructions, adapt the file paths and run your project's existing checks.
---
paths:
- "**/*"
---
# Go Backend Conventions
Applies to: Go HTTP APIs and backend services in this repository.
Version baseline: checked against Go 1.27 (1.26 also supported). Read `go.mod`. The `go` directive decides which language features and standard-library APIs you may use.
## Principles
- Prefer simple, explicit code: plain functions and structs over frameworks and deep abstractions.
- Handle every error where it is returned. Add context with `fmt.Errorf("doing X: %w", err)` and return it, or handle it fully. Never do both (log and return).
- Use composition: embed or hold small types instead of building hierarchies.
- Declare interfaces in the package that consumes them, keep them small, and return concrete types from constructors.
- Use goroutines and channels when they simplify the design, and give every goroutine a clear owner and stop condition.
## HTTP handlers
- Register routes with Go 1.22+ patterns: `mux.HandleFunc("GET /users/{id}", s.handleGetUser)`. Read wildcards with `r.PathValue`.
- Handlers depend on a service or store interface, not on `*sql.DB` directly. SQL lives in the store.
- Map domain errors to status codes in one place and never send internal error text to clients.
```go
type UserStore interface {
GetUser(ctx context.Context, id string) (User, error)
}
type Server struct {
users UserStore
logger *slog.Logger
}
func (s *Server) handleGetUser(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := r.PathValue("id")
user, err := s.users.GetUser(ctx, id)
if errors.Is(err, ErrNotFound) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "user not found"})
return
}
if err != nil {
s.logger.ErrorContext(ctx, "get user", "error", err, "id", id)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
return
}
writeJSON(w, http.StatusOK, user)
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v) // headers are sent; nothing useful to do on failure
}
```
## Errors
- Define sentinel errors for conditions callers branch on (`var ErrNotFound = errors.New("not found")`), and use custom error types when callers need fields.
- The store translates `sql.ErrNoRows` (or `pgx.ErrNoRows`) into `ErrNotFound`, so handlers never import driver packages.
- Check errors with `errors.Is`/`errors.As` (`errors.AsType[T]` on Go 1.26+), never with string comparison.
```go
func (s *Service) GetUser(ctx context.Context, id string) (User, error) {
u, err := s.store.GetUser(ctx, id)
if err != nil {
return User{}, fmt.Errorf("get user %s: %w", id, err)
}
return u, nil
}
```
## Concurrency
- Pass `ctx` as the first parameter and respect cancellation in loops and blocking calls.
- Use `errgroup.WithContext` for fan-out that must stop on the first error, and `g.SetLimit(n)` to bound parallelism.
- Since Go 1.22, loop variables are per-iteration, so don't add `item := item` copies.
```go
func ProcessItems(ctx context.Context, items []Item) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8)
for _, item := range items {
g.Go(func() error { return processItem(ctx, item) })
}
return g.Wait()
}
```
- Protect shared state with a mutex, or confine it to one goroutine. Run tests with `-race`.
## Tests
- Table-driven tests with `t.Run`. Use `httptest` for handlers and fakes of the small interfaces for stores.
## Verify before finishing
Run when available: `gofmt -l .` (no output), `go vet ./...`, `go test -race ./...`, and the repository's linter (`staticcheck` or `golangci-lint run`) if configured.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Imports with @path can nest up to four hops deep, according to the docs. Claude Code can read AGENTS.md as project instructions without extra configuration, but by default only when there is no CLAUDE.md in the working directory or above it. The docs list this behavior for version 2.1.277 and later and describe a setting (claude-md-and-agents-md) that loads both files. If you maintain AGENTS.md for other tools, you can also import it from CLAUDE.md with @AGENTS.md.
Documentation checked 2026-11-05: Claude Code docs: Manage Claude's memory
Stack-neutral CLAUDE.md conventions for Claude Code covering how to read before editing, keep diffs scoped, debug from a reproduction, test and report verification.
Cursor rule for FastAPI projects using Pydantic v2 schemas, SQLAlchemy 2 async_sessionmaker, lifespan cleanup, explicit commits and 409 conflict handling.
Cursor rule for Express 5 APIs in TypeScript with createApp structure, no try/catch boilerplate, Zod 4 validation into res.locals and a safe central error handler.