简述Gin框架集成swagger过程
1、安装 swag
go get github.com/swaggo/swag/cmd/swagswag 用于生成 docs 文件夹(swagger文档程序使用)
安装完成后会在 ${GOPATH}/bin生成一个执行文件
2、安装依赖包
github.com/gin-gonic/gin
github.com/swaggo/gin-swagger3、示例程序
package main
import (
  _ "./docs"
  "github.com/gin-gonic/gin"
  "github.com/swaggo/gin-swagger"
  "github.com/swaggo/gin-swagger/swaggerFiles"
  "net/http"
)
// @title 测试
// @version 0.0.1
// @description  测试
// @BasePath /api/v1/
func main() {
  r := gin.New()
  // 创建路由组
  v1 := r.Group("/api/v1")
  v1.GET("/record/:userId",record)
  // 文档界面访问URL
  // http://127.0.0.1:8080/swagger/index.html
  r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
  r.Run()
}
// Name will print hello name
// @Summary Print
// @Accept json
// @Tags Name12
// @Security Bearer
// @Produce  json
// @Param   some_id     path    int     true        "userId"
// @Resource Name
// @Router /record/{some_id} [get]
// @Success 200 {string} string "ok"
func record(c *gin.Context) {
  c.String(http.StatusOK, "ok")
} 
 
注意:main 方法上的 @BasePath /api/v1/ 和 record 方法 上的@Router /record/{some_id} [get] 并不是像 beego 注解一样用来当方法路由用的,而是swagger 不能识别具体的哪个路由对应哪个方法,所以需要手动指定,供界面的 Try it out 使用
其他参数:参考文档
4、生成文档
在项目执行 swag init
执行 go run main.go
进入 http://127.0.0.1:8080/swagger/index.html 查看文档
目录下 执行命令
swag init自动生成 docs 文件夹,内含 swagger.json 、swagger.json 、 docs.go
 编译不通过,查看报错信息,修改注释。
导入生成的 docs 文件
 即这个 ./docs
                
                










