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

55 lines
2.2 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.
# 12.1 API 响应规范
:::tip 概述
必须遵守的响应契约:统一信封四字段、code 语义、data 形态、命名驼峰(含下划线例外)。机制详解见 [8.1 统一响应格式](../api-spec/response),本节为强制规范条目。
:::
## 强制规范
```text
1. 全部接口返回 {code, ok, msg, data} 四字段信封——禁止裸数组/裸对象
2. 成功 code=0;失败 code=1(细分码在服务端语义,401 原样返回)
3. data 失败时为 {}(非 null);records 为空时为 [](非 null)
4. 分页统一 PageData[T]:{records, total, size, current, pages}
5. 新增返回 {id};修改/删除返回 {}
6. 出入参 json 一律驼峰
唯一例外:登录/令牌接口返回 access_token/refresh_token/expires_in/token_type
(OAuth2 惯例,前端按此读取,禁止"修正"为驼峰)
7. 业务错误经 gerror 上抛由包装层统一 Fail——禁止业务代码手写 JSON 响应
8. 未认证必须 code=401 且 HTTP 401(前端跳登录依赖此约定)
```
## 代码层对应(防呆)
```go
// 响应由 Bind 包装层统一写出——业务只管返回出参与 error
func (s *sExample) Add(ctx context.Context, req *v1.ExampleAddReq) (*v1.ExampleIdRes, error) {
id, err := exampleSpec.Add(ctx, req)
if err != nil {
return nil, err // 包装层 → response.Fail
}
return &v1.ExampleIdRes{Id: id}, nil // 包装层 → response.Ok
}
```
## Review 检查项
```text
□ 新接口返回类型是否用 PageData/IdRes/空结构体(而非自造形态)
□ 错误是否 gerror 上抛(而非手写 {code:1})
□ 字段 json 标签是否驼峰
□ 是否误改了登录接口的下划线字段
□ msg 是否用户可读(前端会弹出)
□ data 为 nil 的路径是否验证过(框架兜底 {} / [])
```
## 反例(禁止)
```text
❌ {"status":200, "result": {...}} 自造信封
❌ {"code":0, "data":null} data null(应 {} / [])
❌ {"code":1003,"msg":"密码错误"} 直接返回细分码 (除 401 外应降级 1,细分在 msg/日志)
❌ 裸数组 [ {...} ] 作为响应体 (应包信封)
❌ {"access_token":...} 改为 accessToken (破坏 OAuth2 惯例)
```