Logo di Go Api Design

Go Api Design

Community
eduardo-sl
go-api-design

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

Panoramica

Autoreeduardo-sl
Repositorygo-agent-skills
Nome della skillgo-api-design
Stelle
86
Fork
11
File inclusi
1
LicenzaMIT
Link
  • Istruzioni in Markdown

    Un file SKILL.md che il modello carica quando serve, consumando token solo quando una richiesta è effettivamente pertinente.

  • Funziona con qualsiasi LLM

    Le skill IA sono in semplice Markdown, non in codice specifico di un fornitore, quindi funzionano con GPT, Claude, Gemini, Grok o un modello locale.

  • 1 file inclusi

    Script, modelli di documento e riferimenti che il modello può leggere mentre lavora. I file sono di sola lettura e non vengono mai eseguiti.

  • Open source

    Pubblicata da eduardo-sl su GitHub. Leggi i sorgenti prima di installarla.

Installazione

Installa la skill IA Go Api Design in TypingMind per usarla con qualsiasi LLM, oppure copiala in un altro agente in grado di leggere SKILL.md.

1

Installa in TypingMind

TypingMind installa una skill direttamente dalla sua cartella GitHub: legge SKILL.md, raccoglie i file delle risorse e salva il risultato in locale.

  1. Apri l'app e vai su Plugin → Skill.
  2. Scegli "Installa da GitHub".
  3. Incolla l'URL della cartella della skill riportato qui sotto e conferma.
    https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(architecture)/go-api-design
  4. Attiva la skill in ogni chat in cui vuoi averla a disposizione.
Plugin → Skill → Nuova skill → Da URL GitHub, poi incolla l'URL della cartella e premi Continua.

Usala in TypingMind

Attiva Go Api Design in qualsiasi chat di TypingMind e al resto pensa il modello. Il nome e la descrizione della skill sono nel prompt di sistema e, non appena arriva una richiesta pertinente, il modello carica da solo le istruzioni complete: non devi mai richiamarla manualmente e non consuma token finché non viene effettivamente usata.

Il modello carica automaticamente Go Api Design non appena riceve una richiesta pertinente.

Funziona con qualsiasi modello IA

Le skill IA sono semplici istruzioni in Markdown, non codice specifico di un fornitore, quindi Go Api Design non è vincolata al modello per cui è stata scritta. Installala una sola volta in TypingMind e usala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modello locale che esegui tu, sempre con le tue chiavi API.

  • Caricata solo quando serve

    Il prompt di sistema contiene solo il nome e la descrizione. Le istruzioni vengono recuperate alla prima richiesta pertinente, quindi una skill inutilizzata non costa nulla.

  • Cambia modello durante la chat

    Poiché la skill è composta da istruzioni e non da codice, continua a funzionare anche se cambi modello: il nuovo modello legge lo stesso file SKILL.md.

Istruzioni della skill

Questo è il contenuto di SKILL.md che il modello carica. Leggilo prima dell'installazione: una skill è un insieme di istruzioni che il tuo modello seguirà.

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.

File inclusi

Il modello legge questi file quando servono, mentre la skill è caricata. Sono accessibili in sola lettura e non vengono mai eseguiti.

Domande frequenti

Cosa fa la skill IA Go Api Design?

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

Perché usare Go Api Design su TypingMind?

Perché la installi una volta e la usi con qualsiasi modello. Go Api Design è scritta in semplice Markdown anziché in codice specifico di un fornitore, quindi la stessa skill funziona con GPT-5, Claude, Gemini, Grok o un modello locale, e puoi cambiare modello durante la chat senza che smetta di funzionare. TypingMind usa le tue chiavi API, quindi paghi direttamente i fornitori anziché un abbonamento per posto utente, e le tue skill e chat restano nel tuo spazio di archiviazione.

Come installo Go Api Design in TypingMind?

Apri Plugin → Skill → Installa da GitHub in TypingMind e incolla https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(architecture)/go-api-design. TypingMind legge il file SKILL.md, include i file associati e installa la skill, che puoi abilitare per ogni singola chat.

Quali modelli IA possono usare Go Api Design?

Qualsiasi modello che colleghi in TypingMind. Le skill IA sono semplici istruzioni in Markdown anziché codice specifico di un fornitore, quindi GPT, Claude, Gemini, Grok e i modelli locali possono tutti caricare questa skill quando una richiesta corrisponde al suo scopo.

Quanti modelli IA posso usare con Go Api Design?

Quanti ne vuoi. Se un modello supporta le skill, puoi usarlo con Go Api Design: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e molti altri, tutti su TypingMind con le tue chiavi API.

La skill IA Go Api Design è gratuita?

Sì. È pubblicata su GitHub da eduardo-sl con licenza MIT. Paghi solo il tuo fornitore IA per i token che usi.

Cosa sono le skill IA?

Una skill IA è un pacchetto di istruzioni riutilizzabili che insegna a un modello IA come svolgere un'attività specifica. Segue il formato aperto Agent Skills: un file SKILL.md con un nome e una descrizione, più eventuali script, modelli o file di riferimento di cui il modello potrebbe aver bisogno. Il modello legge le istruzioni solo quando la tua richiesta corrisponde alla skill, quindi una skill installata non comporta costi finché non viene usata.

In cosa si differenziano le skill IA dai plugin o dai server MCP?

Un plugin o un server MCP fornisce a un modello nuovi strumenti da richiamare: codice che viene eseguito da qualche parte e restituisce un risultato. Una skill IA, invece, fornisce al modello conoscenze e procedure: come affrontare un'attività, quali passaggi seguire e quali caratteristiche deve avere un buon output. Le skill sono semplici istruzioni in Markdown, quindi non richiedono server, chiavi API né ambienti di esecuzione e funzionano con qualsiasi modello.

Vedi tutti

Crea subito la tua area di lavoro IA

Iscriviti alla nostra newsletter per ricevere aggiornamenti sulle nuove funzionalità e sulle prossime iniziative a premi 👇