目的
oapi-codegenを使ってコード自動生成する
準備
-
openapi.yml
作成openapi: 3.0.0 info: title: Go API template version: 0.1.0 servers: - url: http://localhost:8888/api/v1 paths: /album/{id}: get: summary: find album by id parameters: - name: id in: path required: true schema: type: integer responses: '200': description: OK content: application/json: schema: $ref: '#/components/schemas/AlbumResponse' components: schemas: Category: type: object properties: id: type: integer name: type: string enum: - food - music - sports required: - name AlbumResponse: type: object properties: id: type: integer title: type: string Category: $ref: '#/components/schemas/Category'
- oapi-codegenインストール
go install github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest
- GoのバイナリをPATHに追加
export PATH="$(go env GOPATH)/bin:$PATH"
- インストール確認
% oapi-codegen --version github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen v2.4.1
-
config.yml
作成package: API generate: models: true gin-server: true client: true embedded-spec: true output: api/api.gen.go
- 自動生成実行
% oapi-codegen --config=./api/config.yml ./api/openapi.yml
api.gen.go
が生成されていれば成功