本示例演示如何使用 github.com/darkit/gin 的 Swagger 文档生成功能。
OperationIDExample(s)DefaultErrors() 与 ProblemResponse()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().GETDoc("/users", listUsers).
Doc("获取用户列表").
OperationID("listUsers").
Description("分页获取所有用户信息").
Param("page", "query", "integer", "页码", false).
Param("per_page", "query", "integer", "每页数量", false).
Response(200, "成功", []User{}).
ResponseExample(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{})
设置稳定的 OpenAPI operationId,便于 SDK 生成与 AI Agent 调用映射。
.OperationID("createUser")
设置请求体示例。
.RequestExample(User{
Name: "赵六",
Email: "zhaoliu@example.com",
Age: 28,
})
设置响应示例。
.ResponseExample(201, User{
ID: 1,
Name: "赵六",
Email: "zhaoliu@example.com",
Age: 28,
})
快速为路由补充默认错误模型,输出 application/problem+json。
.DefaultErrors(400, 422, 500)
为指定状态码声明 Problem Details 错误模型。
.ProblemResponse(409, "用户冲突")
添加标签(用于分组)
.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 文件,包含:
DefaultErrors() 和 ProblemResponse() 会生成 application/problem+json 文档:id、{id:[0-9]+}、* 等路径段会在 Swagger 中显示为 /users/{id}、/orders/{id}、/files/{_wildcard}