跳至內容

使用 Docker 的 Swagger Codegen

在 Docker 中開發

您可以使用 run-in-docker.sh 來完成所有開發。此指令碼會將您的本機儲存庫對應到 Docker 容器中的 /gen。它也會將 ~/.m2/repository 對應到適當的容器位置。

若要執行 mvn package

終端機視窗
1
git clone https://github.com/swagger-api/swagger-codegen
2
cd swagger-codegen
3
./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-cli
2
./run-in-docker.sh langs # Executes 'langs' command for swagger-codegen-cli
3
./run-in-docker.sh /gen/bin/go-petstore.sh # Builds the Go client
4
./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

先決條件:安裝 VagrantVirtualBox

終端機視窗
1
git clone http://github.com/swagger-api/swagger-codegen.git
2
cd swagger-codegen
3
vagrant up
4
vagrant ssh
5
cd /vagrant
6
./run-in-docker.sh mvn package

公開預先建置的 Docker 映像檔

Swagger Generator Docker 映像檔

Swagger Generator 映像檔可以作為自託管的網路應用程式和 API 來產生程式碼。此容器可以併入 CI 管線,並且至少需要兩個 HTTP 請求和一些 Docker 編排才能存取產生的程式碼。

範例用法(請注意,這假設已安裝 jq 以進行 JSON 的命令列處理)

終端機視窗
1
# Start container and save the container id
2
CID=$(docker run -d swaggerapi/swagger-generator)
3
# allow for startup
4
sleep 5
5
# Get the IP of the running container
6
GEN_IP=$(docker inspect --format '{{.NetworkSettings.IPAddress}}' $CID)
7
# Execute an HTTP request and store the download link
8
RESULT=$(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 file
12
curl $RESULT > result.zip
13
# Shutdown the swagger generator image
14
docker stop $CID && docker rm $CID

在上述範例中,result.zip 將包含產生的用戶端。

Swagger Codegen CLI Docker 映像檔

Swagger Codegen 映像檔作為獨立可執行檔。它可以替代透過 Homebrew 安裝,或者適合無法安裝 Java 或升級已安裝版本的開發人員使用。

若要使用此映像檔產生程式碼,您需要將本機位置掛載為磁碟區。

範例

終端機視窗
1
docker 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 下。