Go Api Designのロゴ

Go Api Design

コミュニティ
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).

概要

公開者eduardo-sl
リポジトリgo-agent-skills
スキル名go-api-design
スター
86
フォーク
11
同梱ファイル
1
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 1個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    eduardo-slがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Go Api Design」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(architecture)/go-api-design
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。

TypingMindで使用

TypingMindのチャットでGo Api Designを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にGo Api Designを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Go Api Designは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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.

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「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).

TypingMindでGo Api Designを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Go Api Designはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにGo Api Designをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/eduardo-sl/go-agent-skills/tree/main/skills/(architecture)/go-api-designを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Go Api Designを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Go Api Designで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもGo Api Designを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Go Api Design」は無料ですか?

はい。eduardo-slがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇