使用 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/(官方 Web 服务)
- https://hub.docker.com/r/swaggerapi/swagger-codegen-cli/(官方 CLI)
Swagger Generator Docker 镜像
Swagger Generator 镜像可以用作自托管的 Web 应用程序和 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
下。