iris框架集成swagger

iris集成swagger

手动编写or自动生成?

  • swagger editor

  • go-swagger工具根据注释生成yaml文档–>swagger UI展示

    swaggo工具

    1. 支持Iris框架(go-swagge使用者较多,但是目前稳定版本不支持mod)
    2. 不需要手动调用一遍api才能生成文档
    3. 解析注释。
    4. 引入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"))
}
源码地址

iris-contrib

注释规范

https://swaggo.github.io/swaggo.io/declarative_comments_format/

https://github.com/swaggo/swag

欢迎访问个人站

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值