Gin之使用swagger生成接口文档
1.下载安装依赖
go get -u github.com/swaggo/swag/cmd/swag (swag cli)
go get github.com/swaggo/gin-swagger (gin-swagger)
go get github.com/swaggo/gin-swagger/swaggerFiles (swagger内置文件)
注:生成的依赖都在pkg目录下
2.swagger介绍
3.使用步骤
4.写注释
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService https://razeen.me
// @contact.name Razeen
// @contact.url https://razeen.me
// @contact.email me@razeen.me
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host 127.0.0.1:8080
// @BasePath /api/v1
func main() {
r := gin.Default()
r.GET("/someJSON", func(c *gin.Context) {
//自定义map
data := map[string]interface{}{
"name": "小王子",
"message": "helloworld",
"age": 18,
}
c.JSON(http.StatusOK, data)
})
r.Run()
}
生成接口文档
输入;swag init
输入以上命令后,项目根目录下会自动生成一个docs文件夹,里面有3个文件夹(爆红的原因是是需要一些额外的依赖)
4.引入gin-swagger渲染文档数据
在main函数的import里新加两个依赖:
gs "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
并注册swagger api相关路由,再写下如下代码
r.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))
终端里输入 go mod tidy
package main
import (
"github.com/gin-gonic/gin"
gs "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
"net/http"
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService https://razeen.me
// @contact.name Razeen
// @contact.url https://razeen.me
// @contact.email me@razeen.me
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host 127.0.0.1:8080
// @BasePath /api/v1
func main() {
r := gin.Default()
r.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))
r.GET("/someJSON", func(c *gin.Context) {
//自定义map
data := map[string]interface{}{
"name": "小王子",
"message": "helloworld",
"age": 18,
}
c.JSON(http.StatusOK, data)
})
r.Run()
}
5.查看文档
把你的项目程序运行起来,打开浏览器访问http://localhost:8080/swagger/index.html就能看到Swagger 2.0 Api文档了。