Swagger
是全球最大的OpenAPI
规范(OAS)API开发工具框架,支持从设计和文档到测试和部署的整个API生命周期的开发。
接口规范swagger2.0(aka openAPI 2.0),https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md。
使用Swagger,就是把相关的API信息存储在它定义的描述文件里面(yml或json格式),再通过维护这个描述文件可以去更新接口文档,以及生成各端代码。
生成yaml或json描述文档的方法:可以手动编辑(通过swagger-editor或vim等);也可在代码中增加规则指定的注释,然后利用工具自动生成json或yaml。
swagger提供的工具:
Swagger Editor: Swagger描述文件的编辑器,支持实时更新。也提供了在线编辑器和本地部署编辑器两种方式。
Swagger UI:提供了一个可视化的UI页面展示描述文件,可以在该页面中对相关接口进行查阅和做一些简单的接口请求。该项目支持在线导入描述文件和本地部署UI项目。
Swagger Codegen: 通过Codegen 可以将描述文件生成html格式和cwiki形式的接口文档,同时也能生成多钟语言的服务端和客户端的代码。
Swagger Inspector: 一个可以对接口进行测试的在线版的postman。比在Swagger UI里面做接口请求,会返回更多的信息,也会保存你请求的实际请求参数等数据。
Swagger Hub:集成了上面所有项目的各个功能,你可以以项目和版本为单位,将你的描述文件上传到Swagger Hub中。在Swagger Hub中可以完成上面项目的所有工作,需要注册账号,分免费版和收费版。
go build -o swagger cmd/swagger/swagger.go cp swagger ~/go/bin
使用
$ swagger -h Usage: swagger [OPTIONS] <command> Swagger tries to support you as best as possible when building APIs. It aims to represent the contract of your API with a language agnostic description of your application in json or yaml. Application Options: -q, --quiet silence logs --log-output=LOG-FILE redirect logs to file Help Options: -h, --help Show this help message Available commands: diff diff swagger documents expand expand $ref fields in a swagger spec flatten flattens a swagger document generate generate go code init initialize a spec document mixin merge swagger documents serve serve spec and docs validate validate the swagger document version print the version
校验
swagger validate autodoc.yml
UI server
Usage: swagger [OPTIONS] serve [serve-OPTIONS] serve a spec and swagger or redoc documentation ui Application Options: -q, --quiet silence logs --log-output=LOG-FILE redirect logs to file Help Options: -h, --help Show this help message [serve command options] --base-path= the base path to serve the spec and UI at -F, --flavor=[redoc|swagger] the flavor of docs, can be swagger or redoc (default: redoc) --doc-url= override the url which takes a url query param to render the doc ui --no-open when present won‘t open the the browser to show the url --no-ui when present, only the swagger spec will be served --flatten when present, flatten the swagger spec before serving it -p, --port= the port to serve this site [$PORT] --host= the interface to serve this site, defaults to 0.0.0.0 [$HOST]
-F=swagger使用 Petstore 托管的 SwaggerUI 打开一个新选项卡。服务器启用了 CORS,并将标准 JSON 的 URL 作为请求字符串附加到 petstore URL。
-F=redoc将文档托管在您自己的计算机上(localhost:port/docs)。
-no-open是为了限制客户端的界面打开(因为多数时候服务都是后台console执行)
swagger serve --host=0.0.0.0 --port=2399 --no-open autodoc.yml
服务端code
swagger generate server [-f ./swagger.json] -A [application-name [--principal [principal-name]]
客户端code
swagger generate client [-f ./swagger.json] -A [application-name [--principal [principal-name]]
参考:
2. golang restful 框架之 go-swagger
3. 使用 SwaggerUI 创建 Golang API 文档
4. Grpc+Grpc Gateway实践三 Swagger了解一下
原文:https://www.cnblogs.com/embedded-linux/p/12589087.html