Cursor rules for standard-library Go services with internal/ layout, graceful shutdown, method-routed handlers, wrapped errors and bounded errgroup work.
.cursor/rules/go-backend-development.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for standard-library Go services with internal/ layout, graceful shutdown, method-routed handlers, wrapped errors and bounded errgroup work."
globs: "**/*"
alwaysApply: false
---
# Go Backend Development
Applies to: Go HTTP services built on the standard library (`net/http`, `log/slog`, `database/sql` or a driver such as pgx).
Version baseline: checked against Go 1.27 (method-aware `ServeMux` and per-iteration loop variables since 1.22, `sync.WaitGroup.Go` since 1.25). Read `go.mod` first and do not use features newer than its `go` directive. Snippets omit import blocks; `user`, `config` and `httpapi` stand for project packages.
## Project layout
```
cmd/server/main.go # wiring: config, logger, DB, server, shutdown
internal/config/ # environment parsing and validation
internal/http/ # handlers, routing, middleware, JSON helpers
internal/user/ # domain types, service, repository interface
internal/postgres/ # repository implementations
go.mod, go.sum
```
- Put application code under `internal/` so other modules cannot import it.
- Create `pkg/` only for code you intend other modules to import; it is not required.
- Organize by domain (`user`, `billing`) rather than by technical layer when packages grow; avoid a catch-all `utils` package.
## main and lifecycle
- `main` only wires dependencies and handles shutdown; keep logic testable outside it.
- Shut down gracefully on SIGINT/SIGTERM so in-flight requests finish.
```go
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
cfg, err := config.Load()
if err != nil {
logger.Error("load config", "err", err)
os.Exit(1)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
srv := &http.Server{
Addr: cfg.Addr,
Handler: httpapi.NewRouter(logger /* , services... */),
ReadHeaderTimeout: 5 * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("listen", "err", err)
stop()
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.Error("shutdown", "err", err)
}
}
```
## Handlers
```go
type Handler struct {
users UserService
logger *slog.Logger
}
func (h *Handler) Routes(mux *http.ServeMux) {
mux.HandleFunc("GET /users/{id}", h.getUser)
}
func (h *Handler) getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
u, err := h.users.Get(r.Context(), id)
switch {
case errors.Is(err, user.ErrNotFound):
writeError(w, http.StatusNotFound, "user not found")
return
case err != nil:
h.logger.ErrorContext(r.Context(), "get user", "id", id, "err", err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, http.StatusOK, u)
}
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 error
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
```
- Decode request bodies with `http.MaxBytesReader` and `json.Decoder` (`DisallowUnknownFields` when the API is strict), then validate before calling the service.
- Return generic messages for 5xx; log the cause with request context.
## Errors
- Wrap with context: `fmt.Errorf("get user %s: %w", id, err)`. Imports go at the top of the file, as usual.
- Define sentinel errors (`var ErrNotFound = errors.New("user: not found")`) in the domain package; repositories translate driver errors (`sql.ErrNoRows`, `pgx.ErrNoRows`) into them.
- Check with `errors.Is`/`errors.As`.
## Concurrency
- Pass `ctx` into every blocking call and stop work when it is cancelled.
- Use `golang.org/x/sync/errgroup` for "run these concurrently, stop on the first error", and `g.SetLimit(n)` to bound concurrency. With Go 1.22+ loop variables, no `item := item` copy is needed.
```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 `sync.Mutex` (keep critical sections small, `defer Unlock`) or confine it to one goroutine that receives on a channel.
- Every goroutine you start must have a way to exit (context, closed channel or finished work).
## Interfaces
- Define interfaces in the package that consumes them, with only the methods it calls; return concrete types from constructors.
```go
type UserRepository interface {
Get(ctx context.Context, id string) (*User, error)
Create(ctx context.Context, u *User) error
}
func NewUserService(repo UserRepository) *UserService { return &UserService{repo: repo} }
```
## Verify before finishing
Run these when they are available in the project:
- `gofmt -l .` (no output) and `go vet ./...`
- `go test -race ./...`
- `staticcheck ./...` or `golangci-lint run`, if configured
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Go 1.27 HTTP service has this rule attached while a developer asks Cursor to add a user endpoint and a batch job that processes items concurrently.
Add GET /users/{id} backed by UserService.Get, and a ProcessItems function that processes up to 8 items at a time and stops on the first error. Make sure the server shuts down cleanly on SIGTERM.Illustrative; not a recorded model run. Routes registered with "GET /users/{id}" and r.PathValue; a handler that maps user.ErrNotFound to 404 and logs other errors before a generic 500; writeJSON/writeError helpers setting Content-Type; errgroup.WithContext with SetLimit(8) and no item := item copy; main using signal.NotifyContext and http.Server.Shutdown with a timeout and ReadHeaderTimeout set; consumer-side repository interface.Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/go-backend-development.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Go Backend Development: Layout, Handlers, Errors and Shutdown project conventions"
globs: "**/*"
alwaysApply: false
---
# Go Backend Development
Applies to: Go HTTP services built on the standard library (`net/http`, `log/slog`, `database/sql` or a driver such as pgx).
Version baseline: checked against Go 1.27 (method-aware `ServeMux` and per-iteration loop variables since 1.22, `sync.WaitGroup.Go` since 1.25). Read `go.mod` first and do not use features newer than its `go` directive. Snippets omit import blocks; `user`, `config` and `httpapi` stand for project packages.
## Project layout
```
cmd/server/main.go # wiring: config, logger, DB, server, shutdown
internal/config/ # environment parsing and validation
internal/http/ # handlers, routing, middleware, JSON helpers
internal/user/ # domain types, service, repository interface
internal/postgres/ # repository implementations
go.mod, go.sum
```
- Put application code under `internal/` so other modules cannot import it.
- Create `pkg/` only for code you intend other modules to import; it is not required.
- Organize by domain (`user`, `billing`) rather than by technical layer when packages grow; avoid a catch-all `utils` package.
## main and lifecycle
- `main` only wires dependencies and handles shutdown; keep logic testable outside it.
- Shut down gracefully on SIGINT/SIGTERM so in-flight requests finish.
```go
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
cfg, err := config.Load()
if err != nil {
logger.Error("load config", "err", err)
os.Exit(1)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
srv := &http.Server{
Addr: cfg.Addr,
Handler: httpapi.NewRouter(logger /* , services... */),
ReadHeaderTimeout: 5 * time.Second,
}
go func() {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("listen", "err", err)
stop()
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.Error("shutdown", "err", err)
}
}
```
## Handlers
```go
type Handler struct {
users UserService
logger *slog.Logger
}
func (h *Handler) Routes(mux *http.ServeMux) {
mux.HandleFunc("GET /users/{id}", h.getUser)
}
func (h *Handler) getUser(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
u, err := h.users.Get(r.Context(), id)
switch {
case errors.Is(err, user.ErrNotFound):
writeError(w, http.StatusNotFound, "user not found")
return
case err != nil:
h.logger.ErrorContext(r.Context(), "get user", "id", id, "err", err)
writeError(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, http.StatusOK, u)
}
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 error
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
```
- Decode request bodies with `http.MaxBytesReader` and `json.Decoder` (`DisallowUnknownFields` when the API is strict), then validate before calling the service.
- Return generic messages for 5xx; log the cause with request context.
## Errors
- Wrap with context: `fmt.Errorf("get user %s: %w", id, err)`. Imports go at the top of the file, as usual.
- Define sentinel errors (`var ErrNotFound = errors.New("user: not found")`) in the domain package; repositories translate driver errors (`sql.ErrNoRows`, `pgx.ErrNoRows`) into them.
- Check with `errors.Is`/`errors.As`.
## Concurrency
- Pass `ctx` into every blocking call and stop work when it is cancelled.
- Use `golang.org/x/sync/errgroup` for "run these concurrently, stop on the first error", and `g.SetLimit(n)` to bound concurrency. With Go 1.22+ loop variables, no `item := item` copy is needed.
```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 `sync.Mutex` (keep critical sections small, `defer Unlock`) or confine it to one goroutine that receives on a channel.
- Every goroutine you start must have a way to exit (context, closed channel or finished work).
## Interfaces
- Define interfaces in the package that consumes them, with only the methods it calls; return concrete types from constructors.
```go
type UserRepository interface {
Get(ctx context.Context, id string) (*User, error)
Create(ctx context.Context, u *User) error
}
func NewUserService(repo UserRepository) *UserService { return &UserService{repo: repo} }
```
## Verify before finishing
Run these when they are available in the project:
- `gofmt -l .` (no output) and `go vet ./...`
- `go test -race ./...`
- `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.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.