Go Web使用pre-commit搭配swaggo/swag
產生Swagger REST API文件。
在「Golang 使用swaggo產生REST API文件」中手動執行swag init
產生Swagger REST API文件,而這裡將透過pre-commit在提交時自動執行。
範例環境:
- Go 1.17
建立Go Web專案及安裝swaggo
參考Golang 使用swaggo產生REST API文件」建立Go web專案及安裝swaggo套件。
安裝pre-commit
參考「使用pre-commit做commit前檢查」安裝pre-commit工具及建立.pre-commit-config.yaml
。
新增swag hooks
pre-commit有提供執行本機script或命令的repository local hooks,因此可依此執行原本以手動執行的swag init
來產生Swagger REST API文件。
在pre-commit設定檔.pre-commit-config.yaml
加入自訂的local swag hooks。
.pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: local # local hooks
hooks:
- id: swag
name: swag
entry: swag init # system command
language: system # use system command
pass_filenames: false # no filenames will be passed to swag hook
files: \.go$ # run go files only, use python regular expressions
description: Generate Swagger REST API documents
測試
在專案根目錄以命令列執行pre-commit install
下載pre-commit的hooks script。
~/../go-demo$ pre-commit install
pre-commit installed at .git/hooks/pre-commit
修改main.go
的swag @description
敘述為Swagger REST API.
並執行git commit,此時pre-commit的swag hooks會對異動的annotation更新swagger文件。
~/../go-demo$ git commit -m "fix swagger general info description"
[INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
Check Yaml...........................................(no files to check)Skipped
Fix End of Files.........................................................Passed
Trim Trailing Whitespace.................................................Passed
swag.....................................................................Failed
- hook id: swag
- files were modified by this hook
2022/01/27 00:39:32 Generate swagger docs....
2022/01/27 00:39:32 Generate general API Info, search dir:./
2022/01/27 00:39:32 create docs.go at docs/docs.go
2022/01/27 00:39:32 create swagger.json at docs/swagger.json
2022/01/27 00:39:32 create swagger.yaml at docs/swagger.yaml
輸入git status
可看到swag hooks修改的swagger文件。
~/../go-demo$ git status
On branch go-web-pre-commit-swag
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: main.go
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: docs/docs.go
modified: docs/swagger.json
modified: docs/swagger.yaml
沒有留言:
張貼留言