什么是swagger
swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 restful web 服务。它使用 yaml 或 json 格式来定义 api 的结构,包括请求、响应、参数等信息。swagger 的主要特点包括:
- 规范性:swagger 定义了一套 api 描述的标准,使得开发者可以以统一的方式描述 api。
- 自动生成文档:swagger 可以自动生成 api 文档,使得开发者和用户可以快速了解 api 的使用方法。
- 交互式文档:swagger 提供了一个交互式的用户界面,用户可以直接在文档中尝试 api 调用。
- 代码生成:swagger 可以根据 api 描述自动生成服务器和客户端的代码,节省开发时间。
- 社区支持:swagger 有广泛的社区支持,许多开发者和公司都在使用它来构建和管理他们的 api。
- 工具链集成:swagger 可以与许多开发工具和平台集成,如 spring boot、.net core、node.js 等。
- 版本控制:swagger 支持 api 的版本控制,使得 api 的迭代更加灵活。
swagger 现在通常与 openapi specification (oas) 结合使用,后者是一个由 linux 基金会支持的开放标准,用于描述 api。swagger 的工具和生态系统现在也支持 oas。
swagger安装
$ go get -u github.com/swaggo/swag/cmd/swag # 1.16 及以上版本 $ go install github.com/swaggo/swag/cmd/swag@latest
gin-swagger
安装
go get -u github.com/swaggo/gin-swagger
使用
想要使用gin-swagger
为你的代码自动生成接口文档,一般需要下面三个步骤:
- 按照swagger要求给接口代码添加声明式注释,具体参照声明式注释格式。
- 使用swag工具扫描代码自动生成api接口文档数据
- 使用gin-swagger渲染在线接口文档页面
添加注释
在程序入口main函数上以注释的方式写下项目相关介绍信息。
package main // @title 这里写标题 // @version 1.0 // @description 这里写描述信息 // @termsofservice http://swagger.io/terms/ // @contact.name 这里写联系人信息 // @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 // @host 这里写接口服务的host // @basepath 这里写base path func main() { r := gin.new() // liwenzhou.com ... r.run() }
在你代码中处理请求的接口函数(通常位于controller层)按如下方式写上注释:
// getcommunityhandler 获取社区列表 // @summary 获取社区列表 // @description 获取社区列表 // @tags 社区列表 // @accept json // @produce json // @param authorization header string true "bearer 用户令牌" // @success 200 {object} models.getcommunitylistparams "成功" // @router /community [get] // @request body models.getcommunitylistparams "社区列表" func getcommunityhandler(c *gin.context) { // 获取社区列表 (community_id, community_name) list list, err := communitylg.getcommunitylist() if err != nil { api.responseerrorwithmsg(c, 200, "获取社区列表失败") return } api.responsesuccess(c, list) }
生成接口文档数据
在项目根目录中运行命令:swag init
,将会解析注解并生成所需的文件(doc
文件夹和docs.go
,swagger.json
,swagger.yaml
)
swag init
执行完命令后,会生成以下文件
./docs ├── docs.go ├── swagger.json └── swagger.yaml
然后在项目代码中注册路由的地方按如下方式引入gin-swagger
相关内容:
import ( _ "project/docs" // 千万不要忘了导入把你上一步生成的docs gs "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerfiles" "github.com/gin-gonic/gin" )
注册swagger api相关路由
r.get("/swagger/*any", gs.wraphandler(swaggerfiles.handler))
项目程序运行起来,打开浏览器访问http://localhost:8080/swagger/index.html就能看到swagger api文档了。
gin-swagger
同时还提供了disablingwraphandler
函数,方便我们通过设置某些环境变量来禁用swagger。例如:
r.get("/swagger/*any", gs.disablingwraphandler(swaggerfiles.handler, "name_of_env_variable"))
可能遇到的问题
在我使用时发现在执行swag init
时,会出现找不到gorm.model的情况。
解决方案:
在命令行加上 --parsedependency --parseinternal
swag init --parsedependency --parseinternal
到此这篇关于gin使用swagger生成接口文档的代码示例的文章就介绍到这了,更多相关gin swagger接口文档内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论