Designs HTTP/REST APIs in Go: handlers, ServeMux routing, middleware, request validation, pagination, idempotency, health checks, error responses, and graceful shutdown. Use when writing HTTP handlers or structuring REST endpoints.
Ships in go-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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-designtakes 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.
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.errors.Is(err, ErrNotFound))
to status codes and logging only the unexpected ones.Content-Type, writes the status
once, and logs encode failures.Middleware is func(http.Handler) http.Handler. Order, outside → inside:
Recoverer → RequestID → Logger → Auth → RateLimit → Handler
Recover MUST be outermost. Auth before business logic. Logger captures timing.
r.Body = http.MaxBytesReader(w, r.Body, 1<<20).400 with a stable message; never echo the decoder's error 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:
/users, not /user/order-items"createdAt") is the default here; match an existing API if one exists/api/v1/.../users/search?q=alice, NOT /searchUserstype 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.
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.http.ErrServerClosed with errors.Is, never ==.main. A log.Fatal inside the serving goroutine skips
every deferred cleanup, including the shutdown itself.// 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.
Consistent error responses across the entire API:
{
"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.
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.http.CrossOriginProtection (Go 1.25+); the go-security-audit skill
owns the details.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/go-agent-skills:go-api-designfrom go-agent-skills
npx claudepluginhub eduardo-sl/go-agent-skills --plugin go-agent-skills35 skills in this plugin
/git-commitStructured git commit messages following Conventional Commits format for Go projects. Generates well-scoped, atomic commits with clear descriptions. Use when committing changes, writing commit messages, preparing PRs, or reviewing commit history quality. Trigger examples: "commit these changes", "create commit", "commit message", "prepare PR", "squash commits". Not for: code review (go-code-review), changelog generation.
/go-architecture-reviewReview Go project architecture: package structure, dependency direction, layering, separation of concerns, domain modeling, and module boundaries. Use when reviewing architecture, designing package layout, evaluating dependency graphs, or refactoring monoliths into modules. Trigger examples: "review architecture", "package structure", "project layout", "dependency direction", "clean architecture Go", "module boundaries". Not for: code-level style (go-coding-standards), endpoint design (go-api-design).
/go-binary-sizeReduce the size of compiled Go binaries and container images: linker flags, inlining budget, CGO and build tags, embedded assets, dependency weight, and measuring what actually costs bytes. Use when a binary or image is too large, when shrinking a CLI for distribution, or when auditing what a dependency adds to the build. Trigger examples: "binary is too big", "shrink the binary", "reduce image size", "strip symbols", "what is making my binary large", "ldflags -s -w". Not for: runtime speed and allocations (go-performance-review), CI setup (go-ci), release pipelines and signing (go-build-release), dependency CVEs (go-dependency-audit).
Other plugins' skills for the same job