在gin项目中使用swaggerAPI构建工具gin使用s

gin使用swaggerAPI构建工具

引用:《Documents are integrated》,《swaggo/swag

创建gin项目

安装

go get -u github.com/gin-gonic/gin
复制代码

编写

// main.go

package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default()
	r.GET("/ping", pang)
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

func pang(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}
复制代码

运行程序

go run main.go
复制代码

创建Swagger

安装依赖

go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/files
go get -u github.com/swaggo/gin-swagger
复制代码

生成swag目录

swag init
复制代码

结构如下:

使用方法参考

项目注释写法参考接口注释写法

在main.go中导入

package main

import (
	_ "SwagTest/docs"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
)

// @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
// @termsOfService http://swagger.io/terms/
func main() {
	r := gin.Default()
	r.GET("/ping", pang)
	url := ginSwagger.URL("http://localhost:8080/swagger/doc.json") // The url pointing to API definition
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

// ShowAccount godoc
// @Summary Show a account
// @Tags Example API
// @Description get string by ID
// @Produce  json
// @Success 200
// @Router /ping [get]
func pang(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

复制代码

重新构建swag

每次修改注释后,需要重新运行构建

swag init
复制代码

运行项目

运行

go run main.go
复制代码

测试地址

http://localhost:8080/swagger/index.html
复制代码