操作系统:Win10
Golang版本:1.15
go get github.com/swaggo/swag/cmd/swag
此时会在环境变量 GOBIN目录中生成swag.exe,如下图所示
验证是否安装成功
F:\Golang\TalentChain\talentchain>swag -v
swag version v1.8.1
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/gin-swagger/swaggerFiles
package main
import (
//.....省略许多包
_ "talentchain/docs" //talentchain是工程的module名称,改成自己工程的module名
)
注:必须导入docs,否则将报错: Failed to load API definition. 如下图所示:
注:注解详情可参见官网文档 Swagger Documentation
// @Summary 摘要
// @Description 描述
// @Description 接口的详细描述
// @Id 全局标识符
// @Version 接口版本号
// @Tags 接口分组,相当于归类
// @Accept json 浏览器可处理数据类型
// @Produce json 设置返回数据的类型和编码
// @Param 参数格式 从左到右:参数名、入参类型、数据类型、是否必填和注释 例:id query int true "ID"
// @Success 响应成功 从左到右:状态码、参数类型、数据类型和注释 例:200 {string} string "success"
// @Failure 响应失败 从左到右:状态码、参数类型、数据类型和注释 例:400 {object} string "缺少参数 ID"
// @Router 路由: 地址和http方法 例:/api/user/{id} [get]
// @contact.name 接口联系人
// @contact.url 联系人网址
// @contact.email 联系人邮箱
query 形如 /user?userId=1016
body 需要将数据放到 body 中进行请求
formData multipart/form-data* 请求
path 形如 /user/1016
header header头信息
上面对基本注解进行了解释,下面在代码中增加注解
package main
import (
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
"talentchain/controller"
_ "talentchain/docs"
)
// @title 人企上链接囗文档
// @version 1.0
// @description 人企上链项目
// @termsofservice https://github.com/xxxx
// @contact.name Tracy
// @contact.email [email protected]
// @host 127.0.0.1:9090
func main() {
r := gin.Default()
r.POST("/labourer/register",controller.Register)
r.Run(":9090")
}
// @Summary 个人注册
// @title Swagger API
// @version 1.0
// @Tags 劳动者管理
// @description 个人注册接囗
// @BasePath /labourer/register
// @Host 127.0.0.1:9090
// @Produce json
// @Param phone body LabourerInfo true "劳动者信息"
// @Success 200 {object} RespData "{"code":200,"data":{},"msg":"ok"}"
// @Router /labourer/register [post]
func Register(c *gin.Context) {
// to do something
}
# 添加swagger访问路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
package main
import (
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
"talentchain/controller"
_ "talentchain/docs"
)
// @title 人企上链接囗文档
// @version 1.0
// @description 人企上链项目
// @termsofservice https://github.com/xxxx
// @contact.name Tracy
// @contact.email [email protected]
// @host 127.0.0.1:9090
func main() {
r := gin.Default()
// 添加swagger访问路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.POST("/labourer/register",controller.Register)
r.Run(":9090")
}
swag init
将会生成一个docs文件夹,下面生成3个文件,如下所示:
F:\Golang\TalentChain\talentchain>tree /F docs
文件夹 PATH 列表
卷序列号为 00000040 0CA4:1102
F:\GOLANG\TALENTCHAIN\TALENTCHAIN\DOCS
docs.go
swagger.json
swagger.yaml
注:每次添加或修改注解后,都需要使用swag init命令重新生成文档,使其生效
启动工程,在浏览器中输入地址:http://127.0.0.1:9090/swagger/index.html
点击接囗右侧展开按钮
点击"Try it out"按钮
查看响应结果
参见官网文档 Swagger Documentation