该功能参考github开源项目gin-swagger,github地址如下:GitHub - swaggo/gin-swagger: gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
生成swagger文档
编写代码注释
代码注释的字段参考:DeclarativeCommentsFormat · GitBook
代码注释分为两种:
General API info 的注释需要放在main函数的前面编写,主要是对API功能的一些基本介绍等等。
// @title 质检中心API接口
// @version 1.0
// @description 质检中心API接口——质检任务列表相关接口
// @contact.name xxx
// @contact.email xxx@lenovo.com
// @BasePath /hoicee/cqi/api
func main() {
...
}
而API Operation则可以写在每个api处理方法前,用于写明API的功能,接收的参数类型,参数列表等等
// QueryTaskList godoc
// @Summary 请求质检任务列表
// @Description 获取质检任务列表
// @Accept json
// @Produce json
// @Param appKey query string true "appKey"
// @Param timestamp query int true "时间戳"
// @Param sign query string true "签名"
// @Param jsonStr query object true "请求参数"
// @Success 200 {object} api.TaskListResponseData
// @Failure 400 {object} api.ResponseBase
// @Failure 404 {object} api.ResponseBase
// @Failure 500 {object} api.ResponseBase
// @Router /v1/items/list [get]
func ProcessQueryTaskList(c *gin.Context) {
...
}
重点说明一下Success及Failure的最后一个参数, 如上面例子中的api.TaskListResponseData,其实是对应到你项目中api包下的一个结构体,名字叫做TaskListResponseData,swag会自动解析这个结构体中的json tag,来生成对应的响应结构。
生成swagger文档
1.安装swag
go get -u 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.在main.go的根目录下,执行
此时swag会在main.go的根目录中生成docs目录
该目录中就包含了根据代码注释生成的swagger格式的文档。文件类型包括json、yam两种
引入gin-swagger
在配置gin 路由的代码中,import如下几个包
package
router
import
(
"fmt"
"io"
"cqi/dao"
"cqi/operator/service"
"cqi/utils/gin/midware"
"github.com/gin-gonic/gin"
swaggerFiles
"github.com/swaggo/files"
ginSwagger
"github.com/swaggo/gin-swagger"
_
"cqi/operator/docs"
// docs is generated by Swag CLI, you have to import it.
)
最后的cqi/operator/docs应对应改为swag生成的docs目录
同时在gin路由中增加如下代码:
url := ginSwagger.URL(fmt.Sprintf(
"http://%s/swagger/doc.json"
, listen)) // The url pointing to API definition
router.GET(
"/swagger/*any"
, ginSwagger.WrapHandler(swaggerFiles.Handler, url))
其中listen应对应服务部署的ip及端口。本质上其实是为服务增加了一个/swagger/*any类型的get接口,调用该接口则返回docs目录中的swagger.json。
部署服务
将服务部署到yAPI可以访问的环境上,启动。
此时在浏览器中输入http://{host}:{port}/swagger/doc.json应该就能查看到接口返回了swagger.json的内容。
配置yAPI swagger自动同步
1.登录yAPI,创建好项目。
2.选择项目,在上面的功能栏中选择“设置”
3.选择“Swagger自动同步”,并在“项目的swagger json地址”中配置上http://{host}:{port}/swagger/doc.json这个访问接口
4.点击“保存”,此时yAPI就会调用刚才配置的接口并获取swagger格式的文档,解析后在“接口”中展示。并且yAPI会自动同步。
每次当你修改了api注释,重新生成swagger文档并将服务部署到对应的环境中时,yAPI就能够自动进行同步,并调整API