最近在研究Go的Gin框架,本文简单记录怎么整合Swagger。
版本信息:
gin v1.6.3
swag v1.6.7
创建一个Go工程!
首先下载安装Gin以及Swagger依赖包:
go get -u github.com/gin-gonic/gingo get -u github.com/swaggo/swag/cmd/swa
若报以下错:
go get github.com/gin-gonic/gin: module github.com/gin-gonic/gin: Get "https://proxy.golang.org/github.com/gin-gonic/gin/@v/list": dial tcp 172.217.160.113:443:connectex: A connection attempt failed because the connected party did not properly respond after a period of time,or established connection failed because connected host has failed to respond.
则是国内无法访问到Go官方网站https://golang.org/
可替换成国内七牛云的镜像(前提是环境参数set GO111MODULE=on,不然需先执行go env -w GO111MODULE=on):
go env -w GOPROXY=https://goproxy.cn,direct
之后再次下载就成功了
可通过输入命令查看swagger是否下载安装成功:
swag -version
然后在main.go平级下执行命令生成swagger的docs文件夹:
swag init
这里是简单的一个demo:
main.go文件:
package mainimport ("github.com/gin-gonic/gin""github.com/swaggo/gin-swagger""github.com/swaggo/gin-swagger/swaggerFiles""net/http"_ "gin-demo/docs" // 执行swag init生成的docs文件夹路径 _引包表示只执行init函数)func main() {router := gin.Default() // 函数返回的是一个Engine指针,Engine代表的是整个框架的一个实例,查看源码可发现实际就是调用New()方法创建实例,并且为实例添加了Logger和Recovery中间件.// 调用Engine的GET方法(其他请求方式POST PUT DELETE等) 第一个参数为相对路径,第二个参数为多个handlerouter.GET("/test", Test)// swagger访问地址 http://localhost:8080/swagger/index.htmlurl := ginSwagger.URL("http://localhost:8080/swagger/doc.json") // The url pointing to API definition// 添加swagger的路由 不然报错404 page not foundrouter.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))//v1组路由 把Print和Hello方法添加到同一组路由,即访问时需要在前面加上/api/v1v1 := router.Group("/api/v1"){v1.GET("/print", Print)v1.GET("/hello", Hello)}// 不指定ip地址和端口时,默认是监听并在 0.0.0.0:8080 上启动服务,另外的写法还有Run(":8080")、Run("0.0.0.0:8080")、Run("localhost:8080")都是指定http://localhost:8080或者http://127.0.0.1:8080/router.Run()}// @Summary 打印测试功能// @title Swagger Example API// @version 0.0.1// @description This is a sample server Petstore server.// @BasePath /api/v1// @Host 127.0.0.1:8080// @Produce json// @Param name query string true "Name"// @Success 200 {string} json "{"code":200,"data":"name","msg":"ok"}"// @Router /print [get]func Print(c *gin.Context) {var (name string)name = c.Query("name")c.JSON(http.StatusOK, gin.H{"code": http.StatusOK,"msg": "success","data": name,})}// @Summary Hello接口// @Description Hello接口// @Tags 用户信息// @Success 200 {string} json "{"message":"success"}"// @Router /hello [get]func Hello(c *gin.Context) {// 当响应码为200时,返回JSON格式数据c.JSON(http.StatusOK, gin.H {"message": "success",})}// @Summary 测试接口// @Description 描述信息// @Success 200 {string} string "ok"// @Router /test [get]func Test(c *gin.Context) {c.JSON(200, "ok")}
最后需要再次执行swag init,然后访问http://localhost:8080/swagger/index.html

注意事项:
1.假如func方法头标注的swagger注释不正确,在执行swag init会报错,自行根据报错信息去修改;
2.访问swagger控制台报错 404 page not found,是因为没有添加swagger路由router.GET("/swagger/*any",ginSwagger.WrapHandler(swaggerFiles.Handler, url));
3.访问swagger控制台报错Failed to load spec,是因为没有import引入执行swag init生成的swagger的docs文件夹;
附上Swagger的注解:
// @Summary 接口概要说明// @Description 接口详细描述信息// @Tags 用户信息 //swagger API分类标签, 同一个tag为一组// @accept json //浏览器可处理数据类型,浏览器默认发 Accept: */*// @Produce json //设置返回数据的类型和编码// @Param id path int true "ID" //url参数:(name;参数类型[query(?id=),path(/123)];数据类型;required;参数描述)// @Param name query string false "name"// @Success 200 {object} Res {"code":200,"data":null,"msg":""} //成功返回的数据结构, 最后是示例// @Failure 400 {object} Res {"code":200,"data":null,"msg":""}// @Router /test/{id} [get] //路由信息,一定要写上
Go使用Swagger的方式与Java会有区别:Go的Gin框架通过在方法上添加 // 类似注释的方式声明;而Java的Spring框架则通过在类上或者方法上添加注解声明,比如@ApiParam!
文章转载自HorizonLight,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




