К основному содержанию
скилл CX Codex

go-openapi — скилл для Claude Code: что делает и как установить

Настраивает подход spec-first для REST API на Go: генерирует интерфейсы через oapi-codegen, подключает middleware валидации и отслеживает ломающие изменения схемы.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add eduardo-sl/go-agent-skills --skill go-openapi -a claude-code
Открыть на GitHub

Что делает go-openapi

Скилл выстраивает разработку REST API вокруг спецификации как единственного источника правды. Модели данных, интерфейсы сервера и клиенты генерируются через oapi-codegen, исключая ручное дублирование типов. При генерации задаётся строгий режим: хэндлеры реализуют интерфейс api.StrictServerInterface, поэтому любое расхождение сигнатур отлавливается компилятором.

В проект добавляется middleware для валидации входящих запросов по схеме (длина строк, регулярные выражения, обязательные query-параметры), а ответы об ошибках приводятся к формату RFC 9457 (application/problem+json). Ломающие изменения спецификации скилл рекомендует выявлять в CI с помощью oasdiff. Без локального тулчейна Go генерация и проверка контрактов работать не будут.

Какие задачи решает

  • связать спецификацию OpenAPI с генерацией серверного кода в Go
  • проверить входящие HTTP-запросы на соответствие схеме через middleware
  • отловить ломающие изменения API до мержа ветки с помощью oasdiff
  • стандартизировать ответы об ошибках по формату RFC 9457

Примеры запросов агенту

  • Сгенерируй строгий серверный интерфейс и модели из api/openapi.yaml через oapi-codegen
  • Добавь middleware для валидации параметров входящих запросов по схеме OpenAPI
  • Проверь через oasdiff, нет ли ломающих изменений между текущей спецификацией и веткой main

Как установить go-openapi

1Через Skills CLI (Vercel)

npx skills add eduardo-sl/go-agent-skills --skill go-openapi -a claude-code

2Вручную: положить файлы

~/.claude/skills/go-openapi/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/go-openapi/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о go-openapi

Как установить go-openapi в Claude Code?

Выполните команду npx skills add eduardo-sl/go-agent-skills --skill go-openapi -a claude-code. Также можно разместить файл вручную по пути ~/.claude/skills/go-openapi/SKILL.md.

Что делает скилл go-openapi?

Он направляет ИИ-агента при разработке REST API на Go по схеме spec-first: помогает настроить запуск oapi-codegen, валидировать входящий трафик и писать контрактные тесты.

Какие дополнительные инструменты нужны для работы?

Требуется установленный компилятор Go. Утилиты oapi-codegen, oasdiff и линтер спецификаций (vacuum или spectral) скилл устанавливает по мере необходимости.

Исходный текст

SKILL.md · MIT
---
name: go-openapi
description: >
  Spec-first REST development in Go with OpenAPI: generating server
  interfaces and clients with oapi-codegen, request validation middleware,
  RFC 9457 error bodies, contract testing, and detecting breaking API
  changes. Use when the API has or should have an OpenAPI document, when
  wiring code generation into the build, or when a hand-written handler has
  drifted from its published contract. Trigger examples: "OpenAPI", "swagger
  spec", "oapi-codegen", "generate a client from the spec", "validate
  requests against the schema", "breaking API change".
  Not for: handler structure and shutdown (go-api-design), gRPC and protobuf
  (go-grpc), GraphQL schemas and resolvers (go-graphql).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain. oapi-codegen, oasdiff and a spec linter (vacuum or spectral) are installed on demand.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*) Bash(oapi-codegen:*) Bash(oasdiff:*) Bash(vacuum:*)
metadata:
  author: eduardo-sl
  version: "1.0.1"
---

# Go OpenAPI

The spec is the source of truth. Types, routes, and clients are generated from
it — never hand-written alongside it, because two hand-maintained copies of a
contract diverge within one sprint.

## Operating Modes

- **Adopt** — the project has hand-written handlers and no spec, or a spec
  nobody generates from. Introduce generation without a rewrite.
- **Extend** — the pipeline exists. Change the spec, regenerate, implement.
- **Review** — check that handlers, spec, and published client agree, and
  that the change is not silently breaking.

## 1. Choose the Generator Once

| Tool | Use it when |
|---|---|
| `oapi-codegen` | Default. Types + server interface + client, works with `net/http`, chi, echo, gin |
| `ogen` | You want a fully generated, strictly validating server and can accept its opinions |
| `swaggo/swag` | Only for a legacy code-first project you are not converting — annotations generate the spec, so the spec cannot be reviewed before the code exists |

Do not mix. A project with both annotations and a checked-in spec has two
sources of truth again.

## 2. Wire Generation Into the Build

Pin the generator as a module tool (Go 1.24+), so every developer and CI run
uses the same version:

```bash
go get -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen
```

```yaml
# oapi-codegen.yaml
package: api
output: internal/api/openapi.gen.go
generate:
  models: true
  std-http-server: true   # Go 1.22+ ServeMux; use chi-server / echo-server if that is the router
  strict-server: true     # typed request/response structs instead of raw http.ResponseWriter
  embedded-spec: true     # lets the service serve its own spec
output-options:
  skip-prune: false
```

```go
//go:generate go tool oapi-codegen -config oapi-codegen.yaml ../../api/openapi.yaml
```

Commit generated files. Reviewers need to see the diff of a contract change,
and a build must not depend on a generator being installed.

CI must fail when they are stale:

```bash
go generate ./... && git diff --exit-code
```

## 3. Implement the Generated Interface

Strict mode gives typed requests and responses, so the compiler enforces the
contract.

```go
// Generated: type StrictServerInterface interface { GetUser(ctx, GetUserRequestObject) (GetUserResponseObject, error) }

type Server struct{ users UserStore }

var _ api.StrictServerInterface = (*Server)(nil) // compile-time compliance

func (s *Server) GetUser(ctx context.Context, req api.GetUserRequestObject) (api.GetUserResponseObject, error) {
    u, err := s.users.Find(ctx, req.Id)
    if errors.Is(err, ErrNotFound) {
        return api.GetUser404JSONResponse{Title: "user not found", Status: 404}, nil
    }
    if err != nil {
        return nil, fmt.Errorf("find user %s: %w", req.Id, err) // 500 via the error handler
    }
    return api.GetUser200JSONResponse{Id: u.ID, Email: u.Email}, nil
}
```

Rules:

- Assert `var _ api.StrictServerInterface = (*Server)(nil)`. Adding an
  endpoint to the spec then becomes a compile error, not a 404 in staging.
- Return a typed response for every documented status. Return a Go `error`
  only for the undocumented failure path.
- Never edit `*.gen.go`. Every change starts in the YAML.

## 4. Validate Requests Against the Spec

Generated types check shape, not constraints. `minLength`, `pattern`,
`enum`, and `required` on query parameters are enforced only if you add the
validation middleware.

```go
spec, err := api.GetSwagger()
if err != nil {
    return fmt.Errorf("load spec: %w", err)
}
spec.Servers = nil // otherwise the server URL must match exactly

mux := http.NewServeMux()
handler := nethttpmiddleware.OapiRequestValidator(spec)(mux)
```

This rejects malformed input at the boundary with a 400 before any handler
runs. Keep domain validation in the domain — the middleware enforces the
contract, not the business rules.

## 5. Errors: RFC 9457 Problem Details

Define one error schema and reference it from every failure response.

```yaml
components:
  schemas:
    Problem:
      type: object
      required: [type, title, status]
      properties:
        type:   { type: string, format: uri, default: "about:blank" }
        title:  { type: string }
        status: { type: integer }
        detail: { type: string }
        instance: { type: string }
```

Serve it as `application/problem+json`. Never return a bare string, and never
put an internal error message in `detail` — log the wrapped error, return a
stable, safe title.

## 6. Versioning and Breaking Changes

Detect breaking changes mechanically; reviewers miss them.

```bash
go install github.com/oasdiff/oasdiff@latest
oasdiff breaking api/openapi.yaml.base api/openapi.yaml --fail-on ERR
```

Run it in CI against the spec on the main branch. Breaking, in practice:
removing an endpoint or field, narrowing a type, adding a required request
field or a required response field the client must understand, changing a
status code, removing an enum value from a response.

Additive changes are safe. Version the path (`/v2/...`) only when a break is
unavoidable, and keep the previous version serving until clients have moved.

## 7. Contract Testing

The spec is only a contract if something fails when the implementation
disagrees.

```go
func TestGetUser_MatchesSpec(t *testing.T) {
    spec, err := api.GetSwagger()
    require.NoError(t, err)
    spec.Servers = nil

    srv := httptest.NewServer(newTestHandler(t, spec))
    t.Cleanup(srv.Close)

    // Generated client — if the spec changed, this stops compiling
    c, err := api.NewClientWithResponses(srv.URL)
    require.NoError(t, err)

    resp, err := c.GetUserWithResponse(t.Context(), "u-1")
    require.NoError(t, err)
    require.Equal(t, http.StatusOK, resp.StatusCode())
    require.Equal(t, "u-1", resp.JSON200.Id)
}
```

Use the generated client in tests, not a hand-rolled `http.NewRequest`. It
turns contract drift into a compile failure.

## 8. Keep the Spec Reviewable

```bash
vacuum lint -d api/openapi.yaml     # or: spectral lint, redocly lint
```

- One file per API, under `api/`, checked in, reviewed like code.
- Every operation has an `operationId` — it becomes the Go method name.
- Every schema has a `description`; it becomes the godoc on the generated type.
- Split large specs with `$ref` to `components/`, not by generating fragments.

## Verification Checklist

1. Exactly one source of truth: a checked-in spec, no annotation generator alongside it
2. The generator is pinned via the `go.mod` tool directive
3. Generated files are committed and CI fails on `go generate` + `git diff --exit-code`
4. `var _ api.StrictServerInterface = (*Server)(nil)` present
5. No hand edits in `*.gen.go`
6. Request validation middleware installed and covered by a 400 test
7. Errors use a single `Problem` schema, served as `application/problem+json`
8. `oasdiff breaking` runs in CI against the base spec
9. At least one test drives the generated client against the real handler
10. The spec lints clean and every operation has an `operationId`

© eduardo-sl · MIT · eduardo-sl/go-agent-skills

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →
mcp-builder официальный anthropics Скилл проводит через создание MCP-сервера на TypeScript или Python: от изучения протокола до тестов и оценки качества. 130 949установок claude-api официальный anthropics Справочник по Anthropic SDK и API Claude для генерации кода без устаревших параметров и выдуманных методов. 74 198установок lark-im larksuite Скилл подключает Lark IM к агенту: он отправляет сообщения, ищет историю, управляет чатами и файлами. Подойдёт для задач вокруг командных коммуникаций. CX Codex +1 472 900установок lark-event larksuite Слушает события Lark/Feishu и отдаёт их потоком NDJSON. Подходит для ботов, обработчиков сообщений и долгих подписчиков. CX Codex +1 466 800установок caveman-discover JuliusBrussee Находит точки вызова LLM в репозитории и размечает их воркфлоу для Caveman Cloud, чтобы расходы на токены не сливались в одну общую кучу. CX Codex +1 104 400установок migration JuliusBrussee Скилл задаёт правила безопасных миграций схем, данных и API с обязательным откатом. Пригодится при изменениях, где нельзя терять данные или ломать совместимость. CX Codex +1 103 900установок

Из того же набора34

go-context Скилл для ИИ-агента, который проверяет и правит работу с context.Context в Go: отмена, таймауты, значения, типичные ошибки. CX Codex +1 ★ 83звёзд репо go-coding-standards Скилл задаёт для ассистента правила оформления Go-кода на базе Effective Go. Он помогает выстроить порядок импортов, теги структур и ранние возвраты при ревью или написании кода. CX Codex +1 ★ 83звёзд репо go-code-review Скилл проверяет Go-код и PR по структурированному списку: от обработки ошибок до тестов. Запускайте его перед слиянием изменений или для ревью пакета. CX Codex +1 ★ 83звёзд репо go-project-layout Подсказывает, как разложить новый Go-проект по папкам: cmd/, internal/, плоская раскладка для мелких утилит. Пригодится в самом начале, когда структура ещё не сложилась. CX Codex +1 ★ 83звёзд репо go-interface-design Скилл помогает проектировать интерфейсы Go, разделять зависимости и проверять контракты на этапе компиляции. Пригодится при рефакторинге и подготовке к тестированию. CX Codex +1 ★ 83звёзд репо go-grpc Скилл для ИИ-агента, который ведёт разработку gRPC-сервисов на Go: proto-контракты, коды ошибок, дедлайны, интерцепторы и стриминг. CX Codex +1 ★ 83звёзд репо go-graphql Скилл помогает строить GraphQL-серверы на Go с помощью gqlgen. Он предотвращает проблему N+1, задаёт лимиты сложности запросов и организует тонкие резолверы. CX Codex +1 ★ 83звёзд репо go-design-patterns Скилл помогает выбрать идиоматичный паттерн Go для создания объектов, смены поведения и обработки сбоев. Пригодится, когда нужно решить, как структурировать код. CX Codex +1 ★ 83звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой