Antigravity workspace rule for Go microservices with handler, service and repository layers, Go 1.22+ routing, context timeouts, slog and table-driven tests.
.agents/rules/antigravity-go-microservices.md. Downloaded files need to be placed in that repository path.---
trigger: glob
globs: "**/*"
---
# Go Microservices
Applies to: Go services that expose HTTP or gRPC APIs, own a PostgreSQL schema and are deployed as separate processes (for example on Kubernetes).
Version baseline: checked against Go 1.27 (Go 1.26 is also supported). Read `go.mod` first. The `go` directive decides language semantics such as per-iteration loop variables (1.22+). If the module targets an older Go, do not use APIs newer than that version.
## Before editing
- Read `go.mod`, the service's `cmd/<service>/main.go`, and one existing handler, service and repository end to end. Follow the layering already there.
- Check whether the project already uses gRPC, sqlc, a router or a logging wrapper before introducing one. Ask before adding a module dependency.
- For changes that cross services (protobuf messages, events, shared database tables), list every consumer and keep the change backward compatible: add fields, don't rename or remove them in the same release.
## Layering
- Handler: decode and validate the request, call one service method, map errors to status codes. No SQL here.
- Service: business rules. Accepts `context.Context` as the first parameter and depends on small interfaces declared in the service package.
- Repository: database access only (hand-written `database/sql`/pgx, or sqlc-generated queries). Translate driver "no rows" errors into a domain sentinel such as `ErrNotFound`.
```go
package user
import (
"context"
"errors"
"fmt"
"log/slog"
)
var ErrNotFound = errors.New("user not found")
type User struct {
ID string `json:"id"`
Email string `json:"email"`
}
// Repository is declared where it is used.
type Repository interface {
Find(ctx context.Context, id string) (*User, error)
}
type Service struct {
repo Repository
log *slog.Logger
}
func NewService(repo Repository, log *slog.Logger) *Service {
return &Service{repo: repo, log: log}
}
func (s *Service) Get(ctx context.Context, id string) (*User, error) {
u, err := s.repo.Find(ctx, id)
if err != nil {
return nil, fmt.Errorf("get user %s: %w", id, err)
}
return u, nil
}
```
## HTTP handlers
- With Go 1.22+ use method and wildcard patterns on `http.ServeMux` (`mux.HandleFunc("GET /users/{id}", h.GetUser)`) and read wildcards with `r.PathValue("id")`.
- Use `errors.Is`/`errors.As` (or `errors.AsType` on Go 1.26+) on wrapped errors. Do not compare error strings.
- Set `Content-Type`, write the status, then encode. Log encode failures. Do not leak internal error text to clients.
```go
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
u, err := h.svc.Get(r.Context(), r.PathValue("id"))
switch {
case errors.Is(err, user.ErrNotFound):
http.Error(w, "not found", http.StatusNotFound)
return
case err != nil:
h.log.ErrorContext(r.Context(), "get user failed", "error", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(u); err != nil {
h.log.ErrorContext(r.Context(), "encode response", "error", err)
}
}
```
## gRPC (when the service uses it)
- Change `.proto` files first and regenerate code with the project's existing command (look for `buf generate` or a `make proto` target). Never hand-edit generated files.
- Return `status.Error(codes.NotFound, ...)` style errors at the gRPC boundary and keep domain errors inside.
## Context, timeouts and shutdown
- Pass the request `ctx` down every call. Never store a context in a struct.
- Put timeouts on outbound calls (`context.WithTimeout`) and on the server (`ReadHeaderTimeout` at minimum).
- On SIGTERM, stop accepting requests and call `srv.Shutdown(ctx)` with a deadline so in-flight requests finish before the pod is killed.
## Logging
- Use `log/slog` with key/value pairs and the `...Context` methods so request-scoped attributes flow through. Do not log secrets, tokens or full request bodies.
## Concurrency
- Every goroutine needs an owner and a way to stop (context cancellation or a closed channel). Use `golang.org/x/sync/errgroup` for fan-out with error propagation. On Go 1.25+, `sync.WaitGroup.Go` covers the case where no error is needed.
- With `go 1.22` or later in `go.mod`, loop variables are per-iteration. Do not add `v := v` copies.
## Tests
- Write table-driven tests with `t.Run` per case. Fake the `Repository` interface in tests, and use `httptest.NewRecorder` for handlers.
- Cover the not-found, invalid-input and dependency-failure paths, not only success.
## Verify before finishing
Run when available in the project:
- `gofmt -l .` (expect no output) and `go vet ./...`
- `go test -race ./...`
- `staticcheck ./...` or `golangci-lint run` if the repository configures it
- Regenerate code (protobuf/sqlc) and confirm `git diff` shows no unexpected changes in generated files
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.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.
Antigravity
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
An Antigravity agent adds a GET /users/{id} endpoint to an existing Go service that has a repository layer over PostgreSQL and runs on Kubernetes.
go.mod declares go 1.26. Add GET /users/{id} to internal/user. The repository returns pgx.ErrNoRows when missing. Return 404 for missing users, 500 otherwise, and add tests.Illustrative; not a recorded model run. The agent reads the existing layers first, then: the repository maps pgx.ErrNoRows to user.ErrNotFound; Service.Get wraps errors with %w and takes ctx first; the handler is registered as "GET /users/{id}", reads r.PathValue("id"), uses errors.Is for the 404 branch, sets Content-Type and logs with slog ErrorContext without leaking error text; a table-driven test with a fake Repository covers found, not found and repository failure using httptest.NewRecorder; no `v := v` loop copies; the summary lists gofmt, go vet and go test -race results.Google describes Antigravity as its agentic development platform. Antigravity reads workspace rules from AGENTS.md or GEMINI.md and from Markdown files in .agents/rules/, with a trigger front matter field that sets when a rule is active. Global rules live under ~/.gemini/.
.agents/rules/antigravity-go-microservices.mdStarting point, not a tested configuration for your repository. Active when files matching globs are involved (trigger: glob). Review the instructions, adapt the file paths and run your project's existing checks.
---
trigger: glob
globs: "**/*"
---
# Go Microservices
Applies to: Go services that expose HTTP or gRPC APIs, own a PostgreSQL schema and are deployed as separate processes (for example on Kubernetes).
Version baseline: checked against Go 1.27 (Go 1.26 is also supported). Read `go.mod` first. The `go` directive decides language semantics such as per-iteration loop variables (1.22+). If the module targets an older Go, do not use APIs newer than that version.
## Before editing
- Read `go.mod`, the service's `cmd/<service>/main.go`, and one existing handler, service and repository end to end. Follow the layering already there.
- Check whether the project already uses gRPC, sqlc, a router or a logging wrapper before introducing one. Ask before adding a module dependency.
- For changes that cross services (protobuf messages, events, shared database tables), list every consumer and keep the change backward compatible: add fields, don't rename or remove them in the same release.
## Layering
- Handler: decode and validate the request, call one service method, map errors to status codes. No SQL here.
- Service: business rules. Accepts `context.Context` as the first parameter and depends on small interfaces declared in the service package.
- Repository: database access only (hand-written `database/sql`/pgx, or sqlc-generated queries). Translate driver "no rows" errors into a domain sentinel such as `ErrNotFound`.
```go
package user
import (
"context"
"errors"
"fmt"
"log/slog"
)
var ErrNotFound = errors.New("user not found")
type User struct {
ID string `json:"id"`
Email string `json:"email"`
}
// Repository is declared where it is used.
type Repository interface {
Find(ctx context.Context, id string) (*User, error)
}
type Service struct {
repo Repository
log *slog.Logger
}
func NewService(repo Repository, log *slog.Logger) *Service {
return &Service{repo: repo, log: log}
}
func (s *Service) Get(ctx context.Context, id string) (*User, error) {
u, err := s.repo.Find(ctx, id)
if err != nil {
return nil, fmt.Errorf("get user %s: %w", id, err)
}
return u, nil
}
```
## HTTP handlers
- With Go 1.22+ use method and wildcard patterns on `http.ServeMux` (`mux.HandleFunc("GET /users/{id}", h.GetUser)`) and read wildcards with `r.PathValue("id")`.
- Use `errors.Is`/`errors.As` (or `errors.AsType` on Go 1.26+) on wrapped errors. Do not compare error strings.
- Set `Content-Type`, write the status, then encode. Log encode failures. Do not leak internal error text to clients.
```go
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
u, err := h.svc.Get(r.Context(), r.PathValue("id"))
switch {
case errors.Is(err, user.ErrNotFound):
http.Error(w, "not found", http.StatusNotFound)
return
case err != nil:
h.log.ErrorContext(r.Context(), "get user failed", "error", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(u); err != nil {
h.log.ErrorContext(r.Context(), "encode response", "error", err)
}
}
```
## gRPC (when the service uses it)
- Change `.proto` files first and regenerate code with the project's existing command (look for `buf generate` or a `make proto` target). Never hand-edit generated files.
- Return `status.Error(codes.NotFound, ...)` style errors at the gRPC boundary and keep domain errors inside.
## Context, timeouts and shutdown
- Pass the request `ctx` down every call. Never store a context in a struct.
- Put timeouts on outbound calls (`context.WithTimeout`) and on the server (`ReadHeaderTimeout` at minimum).
- On SIGTERM, stop accepting requests and call `srv.Shutdown(ctx)` with a deadline so in-flight requests finish before the pod is killed.
## Logging
- Use `log/slog` with key/value pairs and the `...Context` methods so request-scoped attributes flow through. Do not log secrets, tokens or full request bodies.
## Concurrency
- Every goroutine needs an owner and a way to stop (context cancellation or a closed channel). Use `golang.org/x/sync/errgroup` for fan-out with error propagation. On Go 1.25+, `sync.WaitGroup.Go` covers the case where no error is needed.
- With `go 1.22` or later in `go.mod`, loop variables are per-iteration. Do not add `v := v` copies.
## Tests
- Write table-driven tests with `t.Run` per case. Fake the `Repository` interface in tests, and use `httptest.NewRecorder` for handlers.
- Cover the not-found, invalid-input and dependency-failure paths, not only success.
## Verify before finishing
Run when available in the project:
- `gofmt -l .` (expect no output) and `go vet ./...`
- `go test -race ./...`
- `staticcheck ./...` or `golangci-lint run` if the repository configures it
- Regenerate code (protobuf/sqlc) and confirm `git diff` shows no unexpected changes in generated files
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.
Antigravity truncates any single rule file over 24,000 bytes, and global plus always_on rules share a 20,000-token budget, according to the docs. AGENTS.md (or GEMINI.md) in a workspace directory is one of the documented rule locations, and ~/.gemini/AGENTS.md works globally. Use .agents/rules/ when a rule should only apply in some situations.
Documentation checked 2026-11-05: Google Antigravity docs: RulesGoogle Antigravity home page
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.
Cursor rule for Next.js Route Handlers with Zod 4 safeParse validation, auth and ownership checks, awaited params, bounded pagination and one consistent JSON error shape.