swagger应用

1. swagger简述

Swagger是全球最大的OpenAPI规范(OAS)API开发工具框架,支持从设计和文档到测试和部署的整个API生命周期的开发。OpenAPI 是一个 API 规范,Swagger 则是实现规范的工具。

接口规范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中可以完成上面项目的所有工作,需要注册账号,分免费版和收费版。

2. go-swagger

github: https://github.com/go-swagger/go-swagger.git
使用说明参考:https://goswagger.io/
安装
go build -o swagger cmd/swagger/swagger.go
cp swagger ~/go/bin
-----------------------
go get -u github.com/go-swagger/go-swagger/cmd/swagger

使用

$ 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]]

3. gin-swagger

github: https://github.com/swaggo/gin-swagger.git
gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
1. 安装swag
go get github.com/swaggo/swag/cmd/swag

2. 安装gin-swagger

$ go get -u github.com/swaggo/gin-swagger
$ go get -u github.com/swaggo/files

3. 导入gin-swagger

import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files

4. 示例

// main.go

一定要导入 docs,如“demo/docs"。

注:ginSwagger.URL的port必须和本服务端口相同,doc.json位于默认的docs目录下,本质就是通过GET("/swagger/*any")访问本地端口下的docs/docs.go文件。

docs/docs.go是对json和yaml的封装。

package main

import (
    _ "demo/docs"
    "github.com/gin-gonic/gin"
    "github.com/swaggo/gin-swagger"
    "github.com/swaggo/gin-swagger/swaggerFiles"
    "net/http"
)

func main() {

    r := gin.Default()
    r.POST("/login", login)

//  r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // default: doc.json
//  r.Run(":8888") // default :8080

    // other way
    url := ginSwagger.URL("http://localhost:8888/swagger/doc.json") // the rul pointing to API
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
    r.Run(":8888") // default :8080
}


// @登录
// @Description login
// @Accept  json
// @Produce json
// @Param   username     path    string     true        "username"
// @Param   passwd     path    string     true        "passwd"
// @Success 200 {string} string "ok"
// @Router /login [post]
func login(c *gin.Context){
    username := c.PostForm("username")
    passwd := c.PostForm("passwd")
    c.String(http.StatusOK, "Hello world "+username+"_"+passwd)
}
$go mod init demo

5. 生成api文档

在main.go目录运行swag init,生成docs目录,包含API定义。
.
├── docs
│   ├── docs.go
│   ├── swagger.json
│   └── swagger.yaml
├── go.mod
├── go.sum
└── main.go

注:不同版本swag效果不同,swag@1.7.0时,swag init必须要和main.go在同一目录,而swag@1.5.0则可以直接遍历整个目录下的go文件。

go get -u github.com/swaggo/swag/cmd/swag@v1.5.0

6. 运行

$ go run main.go 
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:    export GIN_MODE=release
 - using code:    gin.SetMode(gin.ReleaseMode)

[GIN-debug] POST   /login                    --> main.login (3 handlers)
[GIN-debug] GET    /swagger/*any             --> github.com/swaggo/gin-swagger.CustomWrapHandler.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8888
[GIN] 2020/04/06 - 20:01:33 | 200 |     392.909µs |             ::1 | GET      "/swagger/index.html"
[GIN] 2020/04/06 - 20:01:34 | 200 |     228.911µs |             ::1 | GET      "/swagger/swagger-ui.css"
[GIN] 2020/04/06 - 20:01:34 | 200 |     819.055µs |             ::1 | GET      "/swagger/swagger-ui-bundle.js"
[GIN] 2020/04/06 - 20:01:34 | 200 |     413.233µs |             ::1 | GET      "/swagger/swagger-ui-standalone-preset.js"
[GIN] 2020/04/06 - 20:01:34 | 200 |     250.205µs |             ::1 | GET      "/swagger/doc.json"
[GIN] 2020/04/06 - 20:01:34 | 200 |    2.352787ms |             ::1 | GET      "/swagger/favicon-32x32.png"

可在http://localhost:8888/swagger/index.html查看接口。

4. windows安装swagger editor

1. windows下安装nodejs。
2. 下载swagger editor并安装
git clone https://github.com/swagger-api/swagger-editor.git  //从github下载swagger-editor

cd swagger-editor //进入到下载的文件夹中
npm install

cd ..  //回退到上一曾目录
http-server swagger-editor  //启动swagger-editor

3. 安装问题

在运行 npm install 命令的时候报错(npm ERR! errno -4048,Error:EPERM:operation not permitted) ?

用管理员权限打开 DOS窗口,运行npm cache clean --force,再运行 npm install

http-server commond not found ?
npm install http-server -g

 

参考:

1. 【转】5分钟了解Swagger

2. golang restful 框架之 go-swagger

3. 使用 SwaggerUI 创建 Golang API 文档

4. Grpc+Grpc Gateway实践三 Swagger了解一下

5. 连载八 为它加上Swagger

6. window安装swagger editor

7. 如何编写基于OpenAPI规范的API文档

posted @ 2020-03-28 20:14  yuxi_o  阅读(1014)  评论(0编辑  收藏  举报