Go 用 oapi-codegen 根据 OpenAPI 规范生成类型安全服务端骨架:接口先行,代码自动生成

test12026-11-020 次阅读

接口先行而不是代码先行

多人协作时,前后端最痛的是“接口对不上”:字段拼错、类型漂移、文档过期。API-first 的做法是先把接口写成 OpenAPI(Swagger)规范,再用 oapi-codegen 根据这份规范生成 Go 的类型定义和服务端骨架。规范变,重新生成即可,编译期就能发现字段不一致。

先写 openapi.yaml

openapi: 3.0.3
info:
  title: Article Service
  version: 1.0.0
paths:
  /articles/{id}:
    get:
      operationId: getArticle
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: integer }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Article' }
components:
  schemas:
    Article:
      type: object
      required: [id, title]
      properties:
        id: { type: integer }
        title: { type: string }
        author: { type: string }

生成服务端骨架

准备一个生成配置,告诉工具要生成哪些东西。

# oapi-codegen.yaml
package: api
generate:
  models: true
  embedded-spec: true
  server: true
output: gen/api.gen.go
oapi-codegen --config oapi-codegen.yaml openapi.yaml

生成后你会拿到 Article 结构体、ServerInterface 接口,以及把请求路由到对应方法的 Handler。你要做的只是实现接口。

实现业务逻辑

package main

import (
    "net/http"
    "strconv"

    "your-module/gen"
)

type server struct{}

func (s *server) GetArticle(w http.ResponseWriter, r *http.Request, id int) {
    art := gen.Article{Id: id, Title: "示例标题", Author: "张三"}
    writeJSON(w, http.StatusOK, art)
}

func writeJSON(w http.ResponseWriter, code int, v interface{}) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(code)
    json.NewEncoder(w).Encode(v)
}

func main() {
    s := &server{}
    h := gen.NewStrictHandler(s, nil)
    http.ListenAndServe(":8080", h)
}

注意 id 已经是 int 类型,路径参数解析、绑定、校验都由生成代码兜底;你只写业务。规范更新后重新生成,如果字段改名,调用方会在编译期直接报错,而不是线上 500。

T

test1

文章作者

接口先行而不是代码先行 多人协作时,前后端最痛的是“接口对不上”:字段拼错、类型漂移、文档过期。API-first 的...

分类
技术
发布时间
2026-11-02
字数
约 1718 字
阅读
0 次