如何用oapi-codegen按标签生成Go的OpenAPI v3多REST接口?
用oapi-codegen按标签拆分生成多个Go接口的正确方法
要实现按标签生成多个独立的Go接口,你之前的配置缺了关键步骤——生成命令必须加上--split-tag参数,同时要确保OpenAPI配置里的tag关联正确,具体操作如下:
1. 修正OpenAPI配置
全局Tag定义
保持你第二种方法的全局tag配置,每个tag通过x-oapi-codegen-server-interface-tag指定要生成的接口名称:
tags: - name: foo description: Operations about foo x-oapi-codegen-server-interface-tag: FooInterface - name: bar description: Operations about bar x-oapi-codegen-server-interface-tag: BarInterface
接口路径关联Tag
注意:接口路径的tags字段要关联全局tag的name值(比如foo),而不是直接写接口名称(比如FooInterface),这是你第一种方法的错误所在。修正后的路径配置:
paths: /foobar: post: tags: - foo # 关联全局tag的name,不是直接写FooInterface operationId: createFoo requestBody: content: application/json: schema: $ref: '#/components/schemas/Foo' responses: 201: content: application/json: schema: $ref: '#/components/schemas/Foo' # 可添加属于bar tag的接口示例 /barbaz: get: tags: - bar operationId: getBar responses: 200: content: application/json: schema: $ref: '#/components/schemas/Bar'
2. 执行生成命令
必须加上--split-tag参数触发按tag拆分接口的逻辑,示例命令:
oapi-codegen --package api --generate types,server --split-tag openapi.yaml > api/server.go
生成结果验证
执行命令后,你会在生成的代码里看到两个独立的接口:
type FooInterface interface { createFoo(w http.ResponseWriter, r *http.Request) } type BarInterface interface { getBar(w http.ResponseWriter, r *http.Request) }
之后你就可以分别实现这两个接口的控制器,无需再维护单一的ServerInterface。
内容的提问来源于stack exchange,提问作者nkmuturi
相关产品推荐
相关产品推荐

