Swaggwr 是一个用于自动生成 Swagger 文档的 Go 工具,它利用 Go 语言的注释来生成 API 文档。以下是使用 Swaggwr 生成 Swagger 文档的基本步骤:
安装 Swaggwr: 在你的 Go 项目中,首先需要安装 Swaggwr 工具。可以使用以下命令进行安装:
go get -u github.com/swaggo/swag/cmd/swag
编写注释:
在你的 Go 源代码中,使用特定的注释格式来描述你的 API。这些注释将被 Swaggwr 用来生成文档。例如,你可以在 main.go 文件中添加如下注释来描述你的 API 服务器信息:
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @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
// @host localhost:8080
// @BasePath /api/v1
生成文档:
使用 swag init 命令来扫描你的代码中的注释,并生成 Swagger 文档。这将在你的项目中创建一个 docs 文件夹,其中包含 docs.go、swagger.json 和 swagger.yaml 文件。
集成 Swagger UI: 在你的路由配置中,添加一个路由来集成 Swagger UI。例如,如果你使用的是 Gin 框架,可以这样做: “`go import ( _ “your_project/docs” // 导入 Swaggwr 生成的 docs 包 “github.com/swaggo/gin-swagger” “github.com/swaggo/gin-swagger/swaggerFiles” “github.com/gin-gonic/gin” )
func main() {
r := gin.Default()
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
} “`
- 访问 Swagger UI:
启动你的应用程序后,你可以通过访问
http://localhost:8080/swagger/index.html来查看和测试你的 API 文档。
以上步骤可以帮助你在你的 Go 项目中集成 Swaggwr,从而自动生成和维护 Swagger 文档。记得在编写注释时遵循 Swaggwr 的注释规范,以确保文档的准确性和完整性。