1. Download Swag for Go by using:
go get -u github.com/swaggo/swag/cmd/swag
2. Add comments to your API source code, See Declarative Comments Format.
例子 :
// @summary 商品搜索(全网、淘宝、京东、拼多多、唯品汇)
// @description 可全网比价,参数p 指定搜索区域
// @param q query string true "关键字"
// @Param p query string false "平台来源"
// @accept json
// @produce json
// @success 200 {string} string "ok"
// @failure 400 "We need param [q]!"
// @failure 404 "API not found"
// @router /g/s [get]
3. Download gin-swagger by using:
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
4. router.go 中添加路由
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
router.GET("/docs/*any", ginSwagger.DisablingWrapHandler(swaggerFiles.Handler, "SwaggerDisabled")) //从环境变量中获取,来是否启动路由
配置 /docs/*any 表示 运行主页 http://localhost:8018/docs/index.html 就可以打开了
5. main函数中添加信息
// @title CPS api
// @version 0.1.0
// @description CPS 项目
// @host localhost:8018
// @contact.url [email protected]
// @contact.name cps team
// @BasePath /api/v1
func main() {
注意: @host 参数 在swagger测试页面请求的地址,
@BasePath 也要配置正确
6. 在项目目录中有main.go之下 执行,生成swagger文件
swag init
7. 测试了