【笔记】Go将Gin整合Swagger自动生成API文档

前言

Go将Gin整合Swagger自动生成API文档学习笔记

下载可执行文件

1
go install github.com/swaggo/swag/cmd/[email protected]

在项目中下载依赖

1
2
go get github.com/swaggo/gin-swagger
go get github.com/swaggo/files

在Gin的路由中添加Swagger的路由

1
2
3
4
5
6
7
8
9
10
11
12
13
import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)

func main() {
app := gin.Default()

app.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

app.Run()
}

在函数前添加Swagger语法的注释

  • 在主函数上添加全局API文档注释
  • 在接口函数上添加接口API文档注释

_ "demo/docs":指定swag init生成的文档目录的相对路径作为包引入

在主函数上添加全局API文档注释

@title:标题
@version:版本号
@description:文档描述
@contact.name:作者名
@contact.email:作者邮箱
@host:访问地址
@BasePath:项目访问路径

在接口函数上添加接口API文档注释

@Summary:接口标题
@Description:接口描述
@Tags:标签
@Param:接口参数

第1个参数:参数变量名
第2个参数

query:请求头携带的参数
body:请求体携带的参数

第3个参数:数据类型
第4个参数:是否是必须,true必须,false不必须
第5个参数:参数描述

@Router /index [get]:路由

第1个参数:请求URL
第2个参数:请求类型

@Produce:请求数据格式
@Success 200 :成功处理的响应

demo/main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "demo/docs"
)

type Request struct {
Key string `json:"key"`
}

type Response struct {
Code string `json:"code"`
Msg string `json:"data"`
}

// @title xxx
// @version v1.0
// @description xxx
// @contact.name xxx
// @contact.email [email protected]
// @host 127.0.0.1:8080
// @basePath /
func main() {
app := gin.Default()

app.GET("/index", Index)
app.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

app.Run()
}

// Index 首页
// @tag xxx模块
// @summary xxx功能
// @description xxx
// @param xxx query Request false "xxx"
// @param xxx body string true "xxx"
// @router /index [get]
// @produce json
// @success 200 {object} Response
func Index(context *gin.Context) {
context.JSON(200, Response{0, "ok"})
}

格式化注释

1
swag fmt

生成文档

  • 每次改动Swagger语法的注释后都需要重新生成文档
1
swag init
  • 会在当前位置自动创建docs目录,并存放生成后的文档

完成

参考文献

哔哩哔哩——枫枫知道
swaggo/swag