0、开发环境
操作系统:Win10
Golang版本:1.15
1、安装swag
go get github.com/swaggo/swag/cmd/swag
此时会在环境变量 GOBIN目录中生成swag.exe,如下图所示
验证是否安装成功
F:\Golang\TalentChain\talentchain>swag -v
swag version v1.8.1
2、安装依赖包
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/gin-swagger/swaggerFiles
3、编写注解及添加访问路由
(1)导入包
package main
import (
//.....省略许多包
_ "talentchain/docs" //talentchain是工程的module名称,改成自己工程的module名
)
(2)编写注解
go-swapper注解规范说明
参数param的几种类型
上面对基本注解进行了解释,下面在代码中增加注解
main函数添加注解
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 xxxx@126.com
// @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
}
(3)添加访问路由
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 xxxx@126.com
// @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")
}
4、生成文档
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
5、浏览器访问
启动工程,在浏览器中输入地址:http://127.0.0.1:9090/swagger/index.html
参见官网文档 Swagger Documentation