# go-api-design

Adopt this skill: https://proskills.md/skills/other/eduardo-sl-go-agent-skills-skills-architecture-go-api-design

Page: https://proskills.md/skills/other/eduardo-sl-go-agent-skills-skills-architecture-go-api-design
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/(architecture)/go-api-design/SKILL.md
size: 7859
upstream: https://github.com/eduardo-sl/go-agent-skills/blob/main/skills/(architecture)/go-api-design/SKILL.md

````text
---
name: go-api-design
description: >
  REST and gRPC API design patterns for Go services. Covers HTTP handlers,
  middleware, routing, request/response patterns, versioning, pagination,
  graceful shutdown, and OpenAPI documentation. Use when designing APIs,
  writing HTTP handlers, implementing middleware, structuring REST
  endpoints, or setting up gRPC services. Trigger examples: "design API",
  "REST endpoints", "HTTP handler", "middleware pattern", "graceful
  shutdown", "gRPC service", "API versioning".
  Not for: 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: "1.1.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.

## 1. HTTP Handler Structure

### Use the standard `http.Handler` interface:

```go
// ✅ Good — method on a struct with dependencies
type UserHandler struct {
    store  UserStore
    logger *slog.Logger
}

func (h *UserHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case http.MethodGet:
        h.handleGet(w, r)
    case http.MethodPost:
        h.handleCreate(w, r)
    default:
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
    }
}
```

### Handler function signature pattern:

```go
// Handler methods return nothing — they write directly to ResponseWriter.
// Errors are handled inside the handler, not returned.
func (h *UserHandler) handleGet(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()

    id := chi.URLParam(r, "id") // or mux.Vars(r)["id"]
    if id == "" {
        h.respondError(w, http.StatusBadRequest, "missing user id")
        return
    }

    user, err := h.store.GetByID(ctx, id)
    if err != nil {
        if errors.Is(err, ErrNotFound) {
            h.respondError(w, http.StatusNotFound, "user not found")
            return
        }
        h.logger.Error("get user", slog.Any("error", err))
        h.respondError(w, http.StatusInternalServerError, "internal error")
        return
    }

    h.respondJSON(w, http.StatusOK, user)
}
```

### JSON response helpers:

```go
func (h *UserHandler) respondJSON(w http.ResponseWriter, status int, data interface{}) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    if err := json.NewEncoder(w).Encode(data); err != nil {
        h.logger.Error("encode response", slog.Any("error", err))
    }
}

func (h *UserHandler) respondError(w http.ResponseWriter, status int, msg string) {
    h.respondJSON(w, status, map[string]string{"error": msg})
}
```

## 2. Middleware Pattern

Middleware wraps handlers. Use the standard `func(http.Handler) http.Handler` signature:

```go
func RequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := r.Header.Get("X-Request-ID")
        if id == "" {
            id = uuid.New().String()
        }
        ctx := context.WithValue(r.Context(), requestIDKey, id)
        w.Header().Set("X-Request-ID", id)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func Recoverer(logger *slog.Logger) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            defer func() {
                if rec := recover(); rec != nil {
                    logger.Error("panic recovered",
                        slog.Any("panic", rec),
                        slog.String("stack", string(debug.Stack())),
                    )
                    http.Error(w, "internal server error", http.StatusInternalServerError)
                }
            }()
            next.ServeHTTP(w, r)
        })
    }
}
```

### Middleware ordering (outside → inside):

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

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

## 3. Request Validation

### Decode and validate in one step:

```go
type CreateUserRequest struct {
    Name  string `json:"name"  validate:"required,min=2,max=100"`
    Email string `json:"email" validate:"required,email"`
}

func decodeAndValidate[T any](r *http.Request) (T, error) {
    var req T
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        return req, fmt.Errorf("decode: %w", err)
    }
    if err := validate.Struct(req); err != nil {
        return req, fmt.Errorf("validate: %w", err)
    }
    return req, nil
}
```

### Limit request body size:

```go
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MB
```

## 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`
- camelCase for JSON fields: `"createdAt"`, `"firstName"`
- 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:"next_cursor,omitempty"`
    HasMore    bool   `json:"has_more"`
}
```

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

## 6. Graceful Shutdown

```go
func main() {
    srv := &http.Server{
        Addr:         ":8080",
        Handler:      router,
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
        IdleTimeout:  120 * time.Second,
    }

    // Start server
    go func() {
        if err := srv.ListenAndServe(); err != http.ErrServerClosed {
            log.Fatalf("server error: %v", err)
        }
    }()

    // Wait for interrupt
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit

    // Graceful shutdown with timeout
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    if err := srv.Shutdown(ctx); err != nil {
        log.Fatalf("shutdown error: %v", err)
    }
    log.Println("server stopped gracefully")
}
```

Programs should exit only in `main()`, preferably at most once.

## 7. Health Check Endpoints

```go
// Liveness: is the process alive?
// GET /healthz → 200 OK

// Readiness: can the process serve traffic?
// GET /readyz → 200 OK or 503 Service Unavailable
func (h *HealthHandler) handleReady(w http.ResponseWriter, r *http.Request) {
    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"})
}
```

## 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.
````

## File: README.md
upstream: https://github.com/eduardo-sl/go-agent-skills/blob/main/README.md

````text
<p align="center">
  <img src="docs/assets/hero.png" alt="go-agent-skills — curated Go skills for AI coding agents" width="100%">
</p>

<p align="center">
  <a href="https://skills.sh/eduardo-sl/go-agent-skills"><img alt="skills" src="https://img.shields.io/badge/skills-35-00ADD8?style=for-the-badge&labelColor=06202B"></a>
  <a href="https://agentskills.io/specification.md"><img alt="spec" src="https://img.shields.io/badge/Agent%20Skills-spec%20compliant-7FE7C4?style=for-the-badge&labelColor=06202B"></a>
  <a href="https://github.com/eduardo-sl/go-agent-skills/actions/workflows/validate.yml"><img alt="ci" src="https://img.shields.io/github/actions/workflow/status/eduardo-sl/go-agent-skills/validate.yml?style=for-the-badge&labelColor=06202B&label=validate"></a>
  <a href="https://github.com/eduardo-sl/go-agent-skills/stargazers"><img alt="stars" src="https://img.shields.io/github/stars/eduardo-sl/go-agent-skills?style=for-the-badge&labelColor=06202B&color=F5C451"></a>
  <a href="LICENSE"><img alt="license" src="https://img.shields.io/badge/license-MIT-8FC7D8?style=for-the-badge&labelColor=06202B"></a>
</p>

<h3 align="center">Curated Go skills for AI coding agents.<br>Idiomatic by default, loaded only when they matter.</h3>

<p align="center">
  <a href="#-quick-start">Quick start</a> ·
  <a href="#-usage">Usage</a> ·
  <a href="#-skills">Skills</a> ·
  <a href="#-how-it-works">How it works</a> ·
  <a href="#-evaluations">Evaluations</a> ·
  <a href="#-customizing">Customizing</a> ·
  <a href="#-faq">FAQ</a> ·
  <a href="#-contributing">Contributing</a>
</p>

```bash
npx skills add eduardo-sl/go-agent-skills
```

---

## Why

AI coding agents write Go that compiles. Writing Go that reads like Go takes
more than that. Left to defaults, an agent returns errors with no context,
declares interfaces next to their only implementation, starts goroutines nothing
ever stops, and reaches for `interface{}` where a type parameter belongs.

**go-agent-skills** gives the agent the judgment an experienced Go reviewer
brings: 35 focused skills grounded in [Effective Go](https://go.dev/doc/effective_go),
[Go Code Review Comments](https://go.dev/wiki/CodeReviewComments), and patterns
from large-scale production Go services. They follow the open
[Agent Skills](https://agentskills.io/) standard, work in any compatible agent,
and load **on demand**. Until a skill is relevant, it costs about 135 tokens.

```go
// ❌ Before: the caller gets "sql: no rows in result set" and nothing else
func (s *Service) User(id int) (*User, error) {
    u, err := s.repo.Find(id)
    if err != nil {
        return nil, err
    }
    return u, nil
}

// ✅ After (go-error-handling + go-context): cancellable, wrapped, still matchable
func (s *Service) User(ctx context.Context, id int) (*User, error) {
    u, err := s.repo.Find(ctx, id)
    if err != nil {
        return nil, fmt.Errorf("find user %d: %w", id, err)
    }
    return u, nil
}
```

### Highlights

- 🎯 **35 skills across six areas.** Code quality, architecture, data, safety and performance, testing, and workflow.
- 🪶 **Progressive disclosure.** About 4,800 tokens of descriptions at startup. Bodies and 62 reference files load only when a task needs them.
- 🧭 **A router for overlap.** `go-skills-router` maps a task to the skill that owns it and draws the line where two overlap.
- 🧪 **Measured, not asserted.** 159 eval cases you run with and without the skills. The difference between the two runs is the result.
- 🔐 **Least privilege.** Every skill declares scoped `allowed-tools`. Review and audit skills cannot write.
- 🔄 **Current with Go.** Covers Go 1.21 through 1.27. A weekly workflow opens an issue when a new Go release ships that `go-modernize` doesn't cover yet.
- 🔌 **Agent-agnostic.** Works in Claude Code, Cursor, Codex, GitHub Copilot, Windsurf, OpenCode, Cline, and more.

---

## 🚀 Quick start

Install with the [`npx skills`](https://skills.sh) CLI. It detects the agents you
have and puts each skill where that agent looks for it. That covers **Claude Code**,
**Cursor**, **Codex**, **GitHub Copilot**, **Windsurf**, **OpenCode**, **Cline**,
and [37+ more agents](https://github.com/vercel-labs/skills#available-agents).

```bash
# Everything, interactive
npx skills add eduardo-sl/go-agent-skills

# Look before you install
npx skills add eduardo-sl/go-agent-skills --list

# Only the skills you want
npx skills add eduardo-sl/go-agent-skills --skill go-code-review --skill go-defensive-coding

# Globally, for every project
npx skills add eduardo-sl/go-agent-skills -g

# Non-interactive, for CI and dotfiles
npx skills add eduardo-sl/go-agent-skills --all -y
```

<details>
<summary><b>Claude Code</b>: plugin marketplace</summary>

```bash
/plugin marketplace add eduardo-sl/go-agent-skills
/plugin install go-agent-skills@eduardo-sl
```

Or install the files directly: `npx skills add eduardo-sl/go-agent-skills -a claude-code`

</details>

<details>
<summary><b>Cursor</b></summary>

```bash
npx skills add eduardo-sl/go-agent-skills -a cursor
```

Cursor auto-discovers skills from `.cursor/skills/` and `.agents/skills/`.

</details>

<details>
<summary><b>GitHub Copilot</b></summary>

```bash
npx skills add eduardo-sl/go-agent-skills -a copilot
```

Copilot auto-discovers skills from `.github/skills/`.

</details>

<details>
<summary><b>Codex</b></summary>

```bash
npx skills add eduardo-sl/go-agent-skills -a codex
```

Codex auto-discovers skills from `~/.agents/skills/` and `.agents/skills/`.

</details>

<details>
<summary><b>Windsurf · OpenCode · Cline</b></summary>

```bash
npx skills add eduardo-sl/go-agent-skills -a windsurf
npx skills add eduardo-sl/go-agent-skills -a opencode
npx skills add eduardo-sl/go-agent-skills -a cline
```

</details>

<details>
<summary><b>Shell installer</b>: no Node required</summary>

```bash
git clone https://github.com/eduardo-sl/go-agent-skills.git
./go-agent-skills/scripts/install.sh /path/to/your-go-project --agent claude

# Preview without changing anything
./go-agent-skills/scripts/install.sh /path/to/project --agent claude --dry-run

# Symlink instead of copying, so a `git pull` updates every project
./go-agent-skills/scripts/install.sh /path/to/project --agent claude --symlink
```

Agents: `claude`, `cursor`, `copilot`, `codex`, `windsurf`. Add `--global` to
install into your home directory.

</details>

<details>
<summary><b>Manual copy</b></summary>

```bash
mkdir -p .claude/skills && cp -r go-agent-skills/skills/*/* .claude/skills/   # Claude Code
mkdir -p .cursor/skills && cp -r go-agent-skills/skills/*/* .cursor/skills/   # Cursor
mkdir -p .github/skills && cp -r go-agent-skills/skills/*/* .github/skills/   # Copilot
mkdir -p .agents/skills && cp -r go-agent-skills/skills/*/* .agents/skills/   # Codex / OpenCode
```

</details>

<details>
<summary><b>Keeping them up to date</b></summary>

```bash
npx skills check      # anything out of date?
npx skills update     # bring them current
npx skills list       # what is installed
npx skills remove go-performance-review
```

</details>

---

## 💬 Usage

There is nothing to learn. Work as usual, and the agent loads a skill when your
task matches its description. Agents that support slash commands can also
invoke a skill directly:

```text
/go-code-review
/go-concurrency-review
```

Real tasks usually need more than one skill. These combinations come from
[`go-skills-router`](skills/(workflow)/go-skills-router/):

| Ask your agent | Skills it loads |
| --- | --- |
| "Review this PR" | `go-code-review` |
| "Build a gRPC service with tests" | `go-grpc` + `go-test-quality` + `go-error-handling` |
| "This endpoint is slow under load" | `go-troubleshooting` + `go-performance-review` + `go-database` |
| "Harden this service before launch" | `go-security-audit` + `go-dependency-audit` + `go-defensive-coding` + `go-ci` |
| "Split this monolith" | `go-architecture-review` + `go-refactoring` + `go-semantic-tools` |
| "Scaffold a new CLI" | `go-project-layou
````
