使用 Docker 的 Swagger Codegen
在 Docker 中開發
您可以使用 run-in-docker.sh
來完成所有開發。此指令碼會將您的本機儲存庫對應到 Docker 容器中的 /gen
。它也會將 ~/.m2/repository
對應到適當的容器位置。
若要執行 mvn package
1git clone https://github.com/swagger-api/swagger-codegen2cd swagger-codegen3./run-in-docker.sh mvn package
現在您可以在工作目錄中存取建置成品。
建置完成後,run-in-docker.sh
將作為 swagger-codegen-cli 的可執行檔。若要產生程式碼,您需要輸出到 /gen
下的目錄(例如 /gen/out
)。例如:
1./run-in-docker.sh help # Executes 'help' command for swagger-codegen-cli2./run-in-docker.sh langs # Executes 'langs' command for swagger-codegen-cli3./run-in-docker.sh /gen/bin/go-petstore.sh # Builds the Go client4./run-in-docker.sh generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml \5 -l go -o /gen/out/go-petstore -DpackageName=petstore # generates go client, outputs locally to ./out/go-petstore
在 Docker 中進行獨立產生器開發
請參閱獨立產生器開發
在 Vagrant 中執行 Docker
先決條件:安裝 Vagrant 和 VirtualBox。
1git clone http://github.com/swagger-api/swagger-codegen.git2cd swagger-codegen3vagrant up4vagrant ssh5cd /vagrant6./run-in-docker.sh mvn package
公開預先建置的 Docker 映像檔
- https://hub.docker.com/r/swaggerapi/swagger-generator/(官方網路服務)
- https://hub.docker.com/r/swaggerapi/swagger-codegen-cli/(官方 CLI)
Swagger Generator Docker 映像檔
Swagger Generator 映像檔可以作為自託管的網路應用程式和 API 來產生程式碼。此容器可以併入 CI 管線,並且至少需要兩個 HTTP 請求和一些 Docker 編排才能存取產生的程式碼。
範例用法(請注意,這假設已安裝 jq
以進行 JSON 的命令列處理)
1# Start container and save the container id2CID=$(docker run -d swaggerapi/swagger-generator)3# allow for startup4sleep 55# Get the IP of the running container6GEN_IP=$(docker inspect --format '{{.NetworkSettings.IPAddress}}' $CID)7# Execute an HTTP request and store the download link8RESULT=$(curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{9 "swaggerUrl": "https://petstore.swagger.io/v2/swagger.json"10}' 'https://127.0.0.1:8188/api/gen/clients/javascript' | jq '.link' | tr -d '"')11# Download the generated zip and redirect to a file12curl $RESULT > result.zip13# Shutdown the swagger generator image14docker stop $CID && docker rm $CID
在上述範例中,result.zip
將包含產生的用戶端。
Swagger Codegen CLI Docker 映像檔
Swagger Codegen 映像檔作為獨立可執行檔。它可以替代透過 Homebrew 安裝,或者適合無法安裝 Java 或升級已安裝版本的開發人員使用。
若要使用此映像檔產生程式碼,您需要將本機位置掛載為磁碟區。
範例
1docker run --rm -v ${PWD}:/local swaggerapi/swagger-codegen-cli generate \2 -i https://petstore.swagger.io/v2/swagger.json \3 -l go \4 -o /local/out/go
(在 Windows 上,將 ${PWD}
取代為 %CD%
)
產生的程式碼將位於目前目錄的 ./out/go
下。