本示例演示如何使用 github.com/darkit/gin 的 Swagger 文档生成功能。
e := gin.New(
gin.EnableSwagger(swagger.SwaggerConfig{
Title: "我的 API",
Description: "API 文档描述",
Version: "v1.0.0",
BasePath: "/api",
Host: "localhost:8080",
Schemes: []string{"http", "https"},
}),
)
e.Router().GET("/users", listUsers).
Doc("获取用户列表").
Description("分页获取所有用户信息").
Param("page", "query", "integer", "页码", false).
Param("per_page", "query", "integer", "每页数量", false).
Response(200, "成功", []User{}).
Tag("用户管理")
启动服务器后,访问:
http://localhost:8080/swaggerhttp://localhost:8080/swagger/doc.json设置路由的简要说明
.Doc("获取用户列表")
设置路由的详细描述
.Description("分页获取所有用户信息,支持按名称搜索")
添加参数定义
参数位置 (in):
query - 查询参数path - 路径参数header - 请求头参数body - 请求体参数参数类型 (typ):
string - 字符串integer - 整数number - 数字boolean - 布尔值array - 数组object - 对象示例:
.Param("id", "path", "integer", "用户ID", true)
.Param("page", "query", "integer", "页码", false)
.Param("X-API-Key", "header", "string", "API密钥", true)
添加带模型的参数定义(用于 body 参数)
.ParamModel("body", "body", "用户信息", true, User{})
添加响应定义
.Response(200, "成功", User{})
.Response(400, "参数错误", ErrorResponse{})
.Response(404, "用户不存在", ErrorResponse{})
添加标签(用于分组)
.Tag("用户管理", "权限管理")
标记为废弃 API
.Deprecated()
设置安全方案
.Security("apiKey")
使用结构体标签来增强文档:
type User struct {
ID int64 `json:"id" description:"用户ID"`
Name string `json:"name" binding:"required" description:"用户名"`
Email string `json:"email" description:"邮箱地址"`
Age int `json:"age" description:"年龄"`
}
json - JSON 字段名description - 字段描述binding:"required" - 标记为必需字段cd examples/swagger-demo
go run main.go
然后访问 http://localhost:8080/swagger 查看 Swagger UI。
详见 main.go 文件,包含: