Skip to main content
skill CX Codex

go-api-design — Claude Code skill for Go HTTP/REST APIs

A skill that steers the agent through Go HTTP handler design: routing, middleware, validation, pagination, graceful shutdown. Useful when you start a REST service or rework one.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add eduardo-sl/go-agent-skills --skill go-api-design -a claude-code
Open on GitHub

What go-api-design does

The skill lays down conventions for Go services built on the standard library. Routing goes through http.ServeMux (Go 1.22+): patterns like "GET /users/{id}" match the method, r.PathValue("id") pulls the wildcard, and the wrong method returns 405 with an Allow header. Handlers are methods on a struct holding dependencies such as the store and logger, not package globals. Domain errors map to status codes at the handler boundary, and internal details stay inside.

Middleware is func(http.Handler) http.Handler with a fixed order: Recoverer outermost, then RequestID, Logger, Auth, RateLimit. Request bodies get capped with http.MaxBytesReader before decoding, and a clean decode is not a valid value — validation happens in the same step, answering 400 with a stable message instead of echoing the decoder's text.

Other sections cover URL naming (plural nouns, kebab-case, version in the path, no verbs), cursor pagination over offset/limit, liveness and readiness endpoints, a consistent error shape, and shutdown on SIGTERM. A reference file references/handlers-and-middleware.md sits inside and loads on demand. The Go toolchain is required; without it the allowed go and gofmt commands go nowhere.

What it helps with

  • lay out REST endpoints across handlers and routes
  • wire a middleware chain in the right order
  • cap the request body and validate the payload
  • switch a large list endpoint to cursor pagination
  • stop the server on SIGTERM without dropping live requests

Example prompts for the agent

  • Design a REST API for an orders service in Go: routes, handlers, middleware
  • Add graceful shutdown on SIGTERM plus /healthz and /readyz endpoints to main.go
  • Rework the user list endpoint to cursor pagination with nextCursor

How to install go-api-design

1Skills CLI (Vercel)

npx skills add eduardo-sl/go-agent-skills --skill go-api-design -a claude-code

2Manually: put the files in place

~/.claude/skills/go-api-design/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/go-api-design/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about go-api-design

How do I install go-api-design in Claude Code?

Run npx skills add eduardo-sl/go-agent-skills --skill go-api-design -a claude-code. The skill lands in ~/.claude/skills/go-api-design/SKILL.md.

What does go-api-design do?

It gives the agent Go HTTP/REST conventions: handler structure, middleware order, request validation, pagination, health endpoints, error responses, and graceful shutdown.

How is it different from go-grpc and go-openapi?

This one covers HTTP/REST. Use go-grpc for gRPC services and go-openapi for spec-first OpenAPI work.

Source text

SKILL.md · MIT
---
name: go-api-design
description: >
  HTTP/REST API design for Go services: handlers, ServeMux routing,
  middleware, request validation, pagination, idempotency, health checks,
  error responses, and graceful shutdown. Use when designing APIs, writing
  HTTP handlers, implementing middleware, or structuring REST endpoints.
  Trigger examples: "design API", "REST endpoints", "HTTP handler",
  "middleware pattern", "graceful shutdown", "API versioning".
  Not for: gRPC services (go-grpc), spec-first OpenAPI work (go-openapi),
  general architecture (go-architecture-review), concurrency in handlers
  (go-concurrency-review).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*)
metadata:
  author: eduardo-sl
  version: "2.0.1"
---

# Go API Design

APIs are contracts. Once published, they're promises. Design them as if
you'll maintain them for a decade — because you probably will.

> Community default. A project skill or agent-config rule that explicitly
> supersedes `go-api-design` takes precedence over this one.

Detailed reference material, loaded on demand:

- `references/handlers-and-middleware.md` — handler structs, JSON response
  helpers, request ID and recoverer middleware, decode-and-validate.

Read a reference file only when the summary below is not enough.

## 1. HTTP Handler Structure

- Route with the standard `http.ServeMux` (Go 1.22+): `"GET /users/{id}"`
  patterns match the method, `r.PathValue("id")` reads the wildcard, and a
  wrong method gets a 405 with `Allow`. A router dependency earns its place
  for middleware groups and sub-routers, not for path parameters.
- Handlers are methods on a struct that holds their dependencies (store,
  logger) — never package globals.
- Handler methods return nothing: they write the response and handle the
  error themselves, mapping domain errors (`errors.Is(err, ErrNotFound)`)
  to status codes and logging only the unexpected ones.
- Route through one JSON helper that sets `Content-Type`, writes the status
  once, and logs encode failures.

## 2. Middleware Pattern

Middleware is `func(http.Handler) http.Handler`. Order, outside → inside:

```text
Recoverer → RequestID → Logger → Auth → RateLimit → Handler
```

Recover MUST be outermost. Auth before business logic. Logger captures timing.

## 3. Request Validation

- Cap the body before decoding: `r.Body = http.MaxBytesReader(w, r.Body, 1<<20)`.
- Decode into a typed request struct, then validate it in the same step —
  a successful decode is not a valid value.
- Reply `400` with a stable message; never echo the decoder's error text.

## 4. URL and Naming Conventions

```text
GET    /api/v1/users          → list users
POST   /api/v1/users          → create user
GET    /api/v1/users/{id}     → get user
PUT    /api/v1/users/{id}     → replace user
PATCH  /api/v1/users/{id}     → partial update
DELETE /api/v1/users/{id}     → delete user

GET    /api/v1/users/{id}/orders → list user orders (nested resource)
```

Rules:
- Plural nouns for resources: `/users`, not `/user`
- Kebab-case for multi-word paths: `/order-items`
- One JSON field convention per API, never mixed — camelCase
  (`"createdAt"`) is the default here; match an existing API if one exists
- Version in URL path: `/api/v1/...`
- No verbs in URLs: `/users/search?q=alice`, NOT `/searchUsers`

## 5. Pagination

```go
type PageRequest struct {
    Cursor string `json:"cursor"`
    Limit  int    `json:"limit"`
}

type PageResponse[T any] struct {
    Items      []T    `json:"items"`
    NextCursor string `json:"nextCursor,omitempty"`
    HasMore    bool   `json:"hasMore"`
}
```

Prefer cursor-based pagination over offset/limit for large datasets.
Offset pagination breaks under concurrent writes.

## 6. Graceful Shutdown

```go
func main() {
    if err := run(context.Background()); err != nil {
        slog.Error("server stopped", slog.Any("error", err))
        os.Exit(1)
    }
}

func run(ctx context.Context) error {
    ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
    defer stop()

    srv := &http.Server{
        Addr:              ":8080",
        Handler:           router,
        ReadHeaderTimeout: 5 * time.Second, // Slowloris guard
        ReadTimeout:       10 * time.Second,
        WriteTimeout:      15 * time.Second,
        IdleTimeout:       120 * time.Second,
    }

    errc := make(chan error, 1)
    go func() { errc <- srv.ListenAndServe() }()

    select {
    case err := <-errc:
        return fmt.Errorf("listen: %w", err) // e.g. port already in use
    case <-ctx.Done():
    }

    // ctx is already cancelled; shutdown needs its own deadline.
    shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
    defer cancel()
    if err := srv.Shutdown(shutdownCtx); err != nil {
        return fmt.Errorf("shutdown: %w", err)
    }
    if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
        return err
    }
    return nil
}
```

- `ReadHeaderTimeout` is the Slowloris defence: without it a client can
  hold a connection open by trickling header bytes. `gosec` G112 flags a
  server that lacks it.
- Compare `http.ErrServerClosed` with `errors.Is`, never `==`.
- Exit only from `main`. A `log.Fatal` inside the serving goroutine skips
  every deferred cleanup, including the shutdown itself.

## 7. Health Check Endpoints

```go
// Liveness: is the process alive? GET /healthz → 200, no dependency checks
// Readiness: should it receive traffic? GET /readyz → 200 or 503
func (h *HealthHandler) handleReady(w http.ResponseWriter, r *http.Request) {
    if h.draining.Load() { // atomic.Bool, set when shutdown starts
        h.respondError(w, http.StatusServiceUnavailable, "shutting down")
        return
    }
    if err := h.db.PingContext(r.Context()); err != nil {
        h.respondError(w, http.StatusServiceUnavailable, "database unavailable")
        return
    }
    h.respondJSON(w, http.StatusOK, map[string]string{"status": "ready"})
}
```

On SIGTERM behind a load balancer: set `draining`, wait one readiness
period so the balancer stops routing, *then* call `srv.Shutdown`.
Shutting down first rejects requests the balancer is still sending. Keep
liveness free of dependency checks — a database outage should not make the
orchestrator restart every replica.

## 8. Error Response Format

Consistent error responses across the entire API:

```json
{
    "error": {
        "code": "VALIDATION_ERROR",
        "message": "invalid request parameters",
        "details": [
            {"field": "email", "message": "must be a valid email"}
        ]
    }
}
```

Map internal errors to HTTP status codes at the handler boundary.
Internal errors should NEVER leak to clients. For a standard shape, use
RFC 9457 problem details (`application/problem+json`) — the go-openapi
skill has the type.

## 9. Idempotency and Browser Clients

- `POST` endpoints that create or charge accept an `Idempotency-Key`
  header: store key → response for a bounded time, replay the stored
  response for a repeated key, and reject a concurrent duplicate with 409.
  Clients and proxies retry; without this, a retry is a double charge.
- APIs called from browsers with cookies need CSRF protection —
  `http.CrossOriginProtection` (Go 1.25+); the go-security-audit skill
  owns the details.

© eduardo-sl · MIT · eduardo-sl/go-agent-skills

Similar skills

All skills for Backend and APIs →

From the same set11

git-commit A skill that makes your agent write commit messages in Conventional Commits style: typed, scoped, imperative. Useful when the repo history has turned into noise. CX Codex +1 ★ 83repo stars go-troubleshooting A skill that walks the agent through Go runtime diagnosis: panics, deadlocks, goroutine and memory leaks, race reports. Useful when a program crashes or hangs and the cause is unclear. CX Codex +1 ★ 83repo stars go-observability A skill that sets conventions for Go service telemetry: structured logs with log/slog, OpenTelemetry traces and metrics, SLO alerts. Useful once a service runs in production and you need to see what it does. CX Codex +1 ★ 83repo stars go-error-handling A skill that tells your agent how to create, wrap and inspect Go errors: %w wrapping, sentinel errors, custom types, errors.Is and errors.As. CX Codex +1 ★ 83repo stars go-context A skill that makes your coding agent handle context.Context in Go correctly: cancellation, timeouts, values and the usual anti-patterns. CX Codex +1 ★ 83repo stars go-project-layout Picks a folder layout for a new Go project: cmd/, internal/, or a flat root for small tools. Useful at the start, before the structure hardens. CX Codex +1 ★ 83repo stars go-grpc A skill that steers your coding agent through gRPC work in Go: proto contracts, error codes, deadlines, interceptors and streaming. CX Codex +1 ★ 83repo stars go-dependency-injection A skill that steers your agent toward constructor injection and a single composition root in main. Useful once globals creep in or tests get hard to write. CX Codex +1 ★ 83repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor