SKILL·3EEDD5

go-openapi

eduardo-sl
更新于 11 days ago
4 次查看
69
9
69
在 GitHub 上查看
wordaitestingapidesign

关于

This skill helps developers implement spec-first REST APIs in Go using OpenAPI. It generates server interfaces and clients with oapi-codegen, provides request validation middleware, and helps detect breaking API changes. Use it when you need to keep your Go implementation synchronized with an OpenAPI specification.

快速安装

Claude Code

推荐
主要方式
npx skills add eduardo-sl/go-agent-skills -a claude-code
插件命令备选方式
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 克隆备选方式
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-openapi

在 Claude Code 中复制并粘贴此命令以安装该技能

技能文档

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

ToolUse it when
oapi-codegenDefault. Types + server interface + client, works with net/http, chi, echo, gin
ogenYou want a fully generated, strictly validating server and can accept its opinions
swaggo/swagOnly 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:

go get -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen
# 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: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:

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

3. Implement the Generated Interface

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

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

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.

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.

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.

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

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

GitHub 仓库

eduardo-sl/go-agent-skills
路径: skills/(architecture)/go-openapi
0
FAQ

常见问题

什么是 go-openapi Skill?

go-openapi 是一个 Claude Skill,作者为 eduardo-sl。Skill 将 Claude 按需加载的说明和资源打包,让 Claude 无需额外提示即可执行与 go-openapi 相关的任务。

如何安装 go-openapi?

使用本页的安装命令:将 go-openapi 作为插件添加到 Claude Code,或将其仓库克隆到 skills 目录,然后重启 Claude 以加载该 Skill。

go-openapi 属于哪个分类?

go-openapi 属于元分类。

go-openapi 可以免费使用吗?

可以。go-openapi 已收录在 AIMCP,可免费安装。

相关推荐技能

content-collections

Content Collections 是一个 TypeScript 优先的构建工具,可将本地 Markdown/MDX 文件转换为类型安全的数据集合。它专为构建博客、文档站和内容密集型 Vite+React 应用而设计,提供基于 Zod 的自动模式验证。该工具涵盖从 Vite 插件配置、MDX 编译到生产环境部署的完整工作流。

查看技能
polymarket

这个Claude Skill为开发者提供完整的Polymarket预测市场开发支持,涵盖API调用、交易执行和市场数据分析。关键特性包括实时WebSocket数据流,可监控实时交易、订单和市场动态。开发者可用它构建预测市场应用、实施交易策略并集成实时市场预测功能。

查看技能
creating-opencode-plugins

该Skill帮助开发者创建OpenCode插件,用于接入命令、文件、LSP等25+种事件。它提供了插件结构、事件API规范和JavaScript/TypeScript实现模式,适合需要拦截操作、扩展功能或自定义事件处理的场景。开发者可通过它快速构建响应式模块来增强OpenCode AI助手的能力。

查看技能
sglang

SGLang是一个专为LLM设计的高性能推理框架,特别适用于需要结构化输出的场景。它通过RadixAttention前缀缓存技术,在处理JSON、正则表达式、工具调用等具有重复前缀的复杂工作流时,能实现极速生成。如果你正在构建智能体或多轮对话系统,并追求远超vLLM的推理性能,SGLang是理想选择。

查看技能