安装 swag
$ go get -u github.com/swaggo/swag/cmd/swag
验证是否安装成功
$ swag -v
swag version v1.1.1
安装 gin-swagger
$ go get -u github.com/swaggo/gin-swagger
$ go get -u github.com/swaggo/gin-swagger/swaggerFiles
编写API注释
以官网文档为范例
// @Summary Add a new pet to the store
// @Description get string by ID
// @Accept json
// @Produce json
// @Param some_id path int true "Some ID"
// @Success 200 {string} string "ok"
// @Failure 400 {object} web.APIError "We need ID!!"
// @Failure 404 {object} web.APIError "Can not find ID"
// @Router /testapi/get-string-by-int/{some_id} [get]
func xxx() {
}
运行生成docs文档
[$ gin-blog]# swag init
2018/03/13 23:32:10 Generate swagger docs....
2018/03/13 23:32:10 Generate general API Info
2018/03/13 23:32:10 create docs.go at docs/docs.go
在根目录下会生成如下目录结构
docs/
├── docs.go
└── swagger
├── swagger.json
└── swagger.yaml
注意啦还没完,重点内容打勾,考试要考
添加文档路由
r.GET("/swagger/*any",ginSwagger.WrapHandler(swaggerFiles.Handler))
在路由页面导入包
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "gg/docs" //这个按你生成的项目根目录如,gg是我的项目名 如果没有这个会报以下错误
"not yet registered swag"