Goa で swagger を表示する方法のメモです。
Goa の Getting Started をベースにした例となります。
Getting Started については、https://memo.koumei2.com/goa/ を参照。
以降、Getting Started が動く環境が構築済みである想定となります。
まず準備として、swagger ファイルを視覚的に見れるよう、適当なディレクトリで swagger-ui を Github から clone します。
git clone git@github.com:swagger-api/swagger-ui.git
次に、Getting Started のあるディレクトリに移動し、デザインファイル (design/design.go) に下記を追記します。
Files("/swagger/{*filepath}", "swagger/dist")他のサイトをいろいろと見てみると、"/swagger/*filepath" という記載が多いですが、少なくとも Goa V3 ではこの記載では正しく動きませんでした。
続いて、clone した swagger-ui ディレクトリを Getting Started のあるディレクトリの直下にコピーします。
※ symboliclink でもよいです
これで準備は整ったので、再度ビルドし直します。
% goa gen calc/design % go build ./cmd/calc
起動します。
./calc
[calcapi] 23:28:05 HTTP "Add" mounted on GET /add/{a}/{b}
[calcapi] 23:28:05 HTTP "gen/http/openapi.json" mounted on GET /openapi.json
[calcapi] 23:28:05 HTTP "swagger/dist" mounted on GET /swagger
[calcapi] 23:28:05 serving gRPC method calc.Calc/Add
[calcapi] 23:28:05 HTTP server listening on "localhost:8000"
[calcapi] 23:28:05 gRPC server listening on "localhost:8080"
上記のように、正常に swagger/dist が calc コマンドに認識されていると、mount した旨表示が出ます。
これで、http://localhost:8000/swagger/ で swagger-ui が参照できるようになりました。
swagger-ui 上でテキストフィールドに http://localhost:8000/openapi.json を指定すれば、Goa が生成した API 仕様が表示できるようになります。
swagger-ui に swagger URL を明示的に指定する
いちいち、swagger-ui で swagger ファイルの URL を指定するのは面倒です。
下記のように swagger/dist/index.html を変更すると、デフォルトの表示 URL を変えることができます。
git diff
diff --git a/dist/index.html b/dist/index.html
index 32169e36..814d4d2a 100644
--- a/dist/index.html
+++ b/dist/index.html
@@ -39,7 +39,7 @@
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
- url: "https://petstore.swagger.io/v2/swagger.json",
+ url: "http://localhost:8000/openapi.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
コメント