iris集成swagger
手动编写or自动生成?
-
swagger editor
-
go-swagger工具根据注释生成yaml文档-->swagger UI展示
swaggo工具
- 支持Iris框架(go-swagge使用者较多,但是目前稳定版本不支持mod)
- 不需要手动调用一遍api才能生成文档
- 解析注释。
- 引入swagger包去解析生成yml文档,进行前端显示 Swagger 格式的api信息和测试api。
安装使用:
$ go get -u github.com/swaggo/swag/cmd/swag
环境变量配置
Path:&GOPATH\bin
进入项目根目录,进行初始化操作,根据注释生成api文档
$ swag init
引入swagger包:
import "github.com/iris-contrib/swagger" // swagger middleware for Iris
import "github.com/iris-contrib/swagger/swaggerFiles" // swagger embed files
_ "cloudview.NPMS.backend/docs" // docs is generated by Swag CLI, you have to import it.
示例
package main
import (
"github.com/kataras/iris"
"github.com/iris-contrib/swagger"
"github.com/iris-contrib/swagger/swaggerFiles"
_ "./docs" // docs is generated by Swag CLI, you have to import it.
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host petstore.swagger.io
// @BasePath /v2
func main() {
app := iris.New()
config := &swagger.Config{
URL: "http://localhost:8080/swagger/doc.json", //The url pointing to API definition
}
// use swagger middleware to
app.Get("/swagger/{any:path}", swagger.CustomWrapHandler(config, swaggerFiles.Handler))
app.Run(iris.Addr(":8080"))
}
Run it, and browser to http://localhost:8080/swagger/index.html,
禁用:
package main
import (
"github.com/kataras/iris"
"github.com/iris-contrib/swagger"
"github.com/iris-contrib/swagger/swaggerFiles"
_ "./docs" // docs is generated by Swag CLI, you have to import it.
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host petstore.swagger.io
// @BasePath /v2
func main() {
app := iris.New()
// use swagger middleware to
app.Get("/swagger/{any:path}", swagger.DisablingWrapHandler(swaggerFiles.Handler, "NAME_OF_ENV_VARIABLE"))
app.Run(iris.Addr(":8080"))
}
源码地址
注释规范
https://swaggo.github.io/swaggo.io/declarative_comments_format/
https://github.com/swaggo/swag