Swagger 是一款强大的 API 文档生成工具,可以帮助开发者轻松创建、管理和展示 RESTful API 文档。在本文中,我们将介绍如何在 Golang 项目中使用 Swagger 来生成 API 文档。
官网地址 : gin-swagger
前提条件
- Golang 开发环境(推荐使用 Go 1.16 或更高版本)
- Go Modules 管理工具
- 已安装的 Git 工具
第一步:安装 Swagger 工具
在开始之前,我们需要安装 Swagger 工具。你可以使用以下命令来安装 Swagger:
安装完成后,可以通过运行以下命令来验证安装是否成功:
第二步:安装 Swaggo 依赖
Swaggo 是一个用于 Golang 的 Swagger 文档生成器。我们需要在项目中安装 Swaggo 依赖:
第三步:编写 API 代码
接下来,我们编写一个简单的 API 示例。在项目根目录下创建一个 main.go 文件,并添加以下内容:
第四步:生成 Swagger 文档
在编写好 API 代码后,我们可以使用 Swaggo 生成 Swagger 文档。在项目根目录下运行以下命令:
运行此命令后,会在项目根目录下生成 docs 文件夹,其中包含生成的 Swagger 文档。
第五步:运行项目并访问 Swagger UI
最后,我们运行项目,并访问 Swagger UI。运行以下命令启动项目:
在浏览器中访问 http://localhost:8080/swagger/index.html,即可看到生成的 Swagger UI 页面,其中包含了我们编写的 API 文档。