统一响应
handler 一律返回 pkg/response 的 R[T] / PageResult[T],用 response.Ok / Fail / FailCode 构造。 不要手写 gin.H 拼响应。
R 结构
go
type R[T any] struct {
Code int // 业务码:200 成功、500 失败、404 不存在、601 警告
Msg string
Data T
}Data不加omitempty,无数据时序列化为null而非省略。- HTTP 状态码恒 200,业务成败靠
code字段区分。middleware.Recover与oplog均按此判定。
快捷构造
| 构造 | 用途 |
|---|---|
response.Ok(data) | 成功,带数据 |
response.OkVoid() | 成功,无数据 |
response.OkMsg(msg) | 成功,带提示文案 |
response.OkMsgData(msg, data) | 成功,提示 + 数据 |
response.Fail(msg) | 失败(code=500) |
response.FailCode(code, msg) | 失败,指定业务码 |
response.Warn(msg) | 警告(code=601) |
分页
分页结果用 repository.PageResult[T]:
go
type PageResult[T any] struct {
Total int64
Rows []T
}pkgrepo.Page(rows, total) 构造。详见 pkg 参考 / repository。
例外
- 导出接口:响应体是二进制 xlsx 附件,不返回
response.R。详见 CRUD 指南 / Handler。 - 探针
/ping:路由内联的gin.H,不算业务接口。