1. 安装
(1) 安装 swag 命令行工具
go install github.com/swaggo/swag/cmd/swag@latest
(2) 安装 Gin 的 Swagger 支持库
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
2. 添加 Swagger 注释
(1) 主入口文件 (main.go) 添加全局注释
// @title My Gin API
// @version 1.0
// @description 这是 Gin 项目的 Swagger 文档
// @contact.name API Support
// @contact.url http://example.com/support
// @contact.email support@example.com
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
package main
import (
"github.com/gin-gonic/gin"
_ "myproject/docs" // 重要!导入生成的 docs 包
)
(2) 控制器方法添加注释示例 (handler/user.go)
// @Summary 创建用户
// @Description 通过表单数据创建新用户
// @Tags users
// @Accept json
// @Produce json
// @Param user body model.CreateUserRequest true "用户信息"
// @Success 200 {object} model.UserResponse
// @Failure 400 {object} errcode.ErrorResponse
// @Failure 500 {object} errcode.ErrorResponse
// @Router /users [post]
// @Security ApiKeyAuth
func CreateUser(c *gin.Context) {
// 业务逻辑…
}
3. 生成 Swagger 文档
在项目根目录执行生成命令:
swag init -g ./main.go --output ./docs
生成以下文件:
docs/
├── docs.go # 文档数据
├── swagger.json # OpenAPI JSON
└── swagger.yaml # OpenAPI YAML
4. 配置 Swagger 路由
r := gin.Default()
// Swagger 路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
5. 访问 Swagger UI
启动服务后访问:
http://localhost:8080/swagger/index.html
本文为原创内容,作者:闲鹤,原文链接:https://blog.uwenya.cc/1595.html,转载请注明出处。