Skip to content
Agentmart
Submit a tool

go-api-design

HTTP/REST API design for Go services: handlers, ServeMux routing, middleware, request validation, pagination, idempotency, health checks, error responses, and…

Skill by eduardo-sl

IndexedMIT★ 82
Write a review

Install

Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.

npx agentmarket install skill/eduardo-sl-go-api-design

Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.

Get the weekly diff

The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.

We use your email only for this newsletter. Privacy

About

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).

Use cases: design, backend, writing

No reviews yet. Installed it? Reviews come from verified installers only. How reviews work

Permissions

What this skill can do and what it asks for, from its SKILL.md and code. Checked Oct 25, 2026.

Tools
No tools found
Secrets
None asked for
Install scripts
None found

Network hosts it talks to 1

  • codeload.github.com · found in install command

Files it touches

  • ~/.claude/skills/go-api-design

Tools it pre-approves 7

From allowed-tools in SKILL.md: the agent may use these without asking you each time.

  • Read
  • Edit
  • Write
  • Glob
  • Grep
  • Bash(go:*)
  • Bash(gofmt:*)

What's inside

Skill 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).
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
Instructions
193 lines in SKILL.md · view on GitHub

Before installing

  • Pre-approves some shell commands

Files (2)

  • SKILL.md
  • handlers-and-middleware.md · references/

SKILL.md (first lines)

# 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)

From eduardo-sl/go-agent-skills, MIT.

More from eduardo-sl/go-agent-skills

Compare and alternatives

    Featured in

    Signals

    Stars
    82
    Forks
    10
    Open issues
    0
    Last commit (this folder)
    Oct 14, 2026 (13 days ago)

    From GitHub (fetched Oct 24, 2026).

    Details

    Version
    2.0.1
    License
    MIT
    First seen
    Oct 24, 2026
    Last checked
    Oct 24, 2026

    More from eduardo-sl

    Cite this page

    go-api-design skill. Agent Mart. https://agentmart.dev/skills/eduardo-sl-go-api-design (last updated 2026-10-24)