可以通过插件生成,这篇文章写的很好:https://www.cnblogs.com/liwenzhou/p/13629767.html
插件安装:go get -u github.com/swaggo/swag/cmd/swag
文档生成:swag init -d ./handler,./model,./common # 指定包含注释的代码目录
使用 Swagger(在 Go 里常用 swaggo/swag)为 Gin 项目自动生成接口文档。步骤如下:
安装 swag 工具:
go install github.com/swaggo/swag/cmd/swag@latest
在项目根目录初始化文档:
swag init
这会生成 docs 目录。
在代码中添加注释:
在每个接口处理函数上方添加类似如下的注释(以 CreateBook 为例):
// @Summary 创建图书
// @Description 新增一本图书
// @Tags books
// @Accept json
// @Produce json
// @Param book body Book true "图书信息"
// @Success 201 {object} Book
// @Failure 400 {object} gin.H
// @Router /api/books [post]
在 main.go 引入 docs 并注册 Swagger 路由:
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/files"
_ "bookstore/docs" // docs 是 swag init 生成的
)
func main() {
// ...原有代码...
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
重新生成文档:
swag init
访问接口文档:
启动服务后,浏览器访问 http://localhost:8080/swagger/index.html 查看接口文档。
浙公网安备 33010602011771号