Files
easygoadmin-wiki/EasyGoAdmin_GoFrame_NaiveVue/zh/api-spec/response.md
T
2026-10-20 21:53:26 +08:00

110 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 8.1 统一响应格式
:::tip 概述
全部接口返回统一 JSON 信封:code/ok/msg/data 四字段。code=0 成功、1 通用失败、401 未认证(配合 HTTP 401);前端按 code 分流。分页用 PageData 泛型壳。
:::
## 信封结构
```json
// 成功
{
"code": 0,
"ok": true,
"msg": "操作成功",
"data": { "id": 1 }
}
// 失败
{
"code": 1,
"ok": false,
"msg": "用户不存在",
"data": {}
}
// 未认证(HTTP 401)
{
"code": 401,
"ok": false,
"msg": "登录已过期,请重新登录",
"data": {}
}
```
## 字段约定
| 字段 | 类型 | 说明 |
|------|------|------|
| code | int | 0=成功;1=通用失败;401=未认证;细分业务码见 8.2(前端主要看 0/1/401) |
| ok | bool | 与 code==0 等价的布尔便捷字段 |
| msg | string | 提示信息;失败时前端弹出 |
| data | object | 业务数据;失败时为空对象 `{}`(非 null) |
## Fail 映射规则
```text
response.Fail(err):
gerror 码 == 401 → 原样保留(配合 HTTP 401,前端跳登录)
其余 → 一律降级 code=1
设计含义:consts 中的细分错误码(1001 用户不存在……)主要用于
日志与服务端语义区分;前端统一按 1 弹 msg 即可。
```
## 分页壳(PageData[T])
```json
{
"code": 0, "ok": true, "msg": "操作成功",
"data": {
"records": [ ... ],
"total": 100,
"size": 10,
"current": 1,
"pages": 10
}
}
```
| 字段 | 说明 |
|------|------|
| records | 行数组;**为空输出 `[]` 而非 null** |
| total | 总条数 |
| size | 每页条数(pageSize,默认 10 上限 500) |
| current | 当前页码(pageNo,默认 1) |
| pages | 总页数 |
## 其他通用出参形态
```text
新增: {"id": 1} (IdRes)
修改/删除:{} (空结构体)
列表(非分页):[ ... ] (数组直接作 data)
详情: { ...单对象... }
```
## 状态页
```text
404 → {"code":1,"msg":"接口不存在: GET /api/xxx"}
500 → {"code":1,"msg":"服务器内部错误"}
非 200 一律输出统一 JSON 信封,不返回 HTML
```
## 前端处理模板
```ts
// 响应拦截器分流(语义示意)
if (code === 0) return data; // 成功解包
if (code === 401) { 跳登录/尝试refresh; }
if (code === 1) ElMessage.error(msg); // 统一弹窗
```
## 开发规约
+ 出参 json 一律驼峰;唯一例外是登录/令牌接口的下划线字段(见 8.6)
+ 业务错误用 gerror.NewCode(consts.Xxx, "消息") 上抛,由 Bind 包装层统一 Fail
+ 不要在业务代码手写 JSON 响应(统一信封在包装层完成)
+ data 为 nil 时框架输出 `{}`/`[]`,业务无需特殊处理