oapi-codegen + echo + go-playground/validator で API サーバのHTTP リクエストの Handlerをテンプレート化した
Repository
https://github.com/nakamurakzz/go-oapi-codegen-template
参考
概要
- docs/api.yaml を元に oapi-codegen で HTTPリクエストのハンドラー、リクエストBory、クエリパラメータの構造体を自動生成している
- バリデーションは go-playground の Struct バリデータを使用
- Struct バリデータに食わせるために、`x-oapi-codegen-extra-tags` を使用している
components:
schemas:
PostBookRequest:
type: object
required:
- title
- author
properties:
title:
type: string
minLength: 1
maxLength: 256
x-oapi-codegen-extra-tags:
validate: "required,min=1,max=256"
author:
type: string
minLength: 1
maxLength: 256
x-oapi-codegen-extra-tags:
validate: "required,min=1,max=256"
description:
type: string
maxLength: 1000
x-oapi-codegen-extra-tags:
validate: "max=1000"
良いところ
- 自動生成最高
- 書き方が決まっている、書く量が少なくなる、そもそもIF仕様をこちらがしっかりと決める必要があり責任分解点が明確などの理由でAIさんとの協業に向いていそう
いまいちなところ
- コード自動生成のための`required` と、バリデーションのための `x-oapi-codegen-extra-tags` を両方定義する必要がある