简述 Gin 框架如何集成swagger

简述Gin框架集成swagger过程
1、安装 swag

go get github.com/swaggo/swag/cmd/swag

swag 用于生成 docs 文件夹(swagger文档程序使用)
安装完成后会在 ${GOPATH}/bin生成一个执行文件
2、安装依赖包
github.com/gin-gonic/gin github.com/swaggo/gin-swagger

3、示例程序
/** * Created by martin on 01/02/2019 */package mainimport ( _ "./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() }// @获取指定ID记录 // @Description get record by ID // @Acceptjson // @Produce json // @Paramsome_idpathinttrue"userId" // @Success 200 {string} string "ok" // @Router /record/{some_id} [get] 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 使用
【简述 Gin 框架如何集成swagger】其他参数:参考文档
4、生成文档 在项目执行 swag init
执行 go run main.go
进入 http://127.0.0.1:8080/swagger/index.html 查看文档

    推荐阅读