Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

响应 envelope

所有响应统一格式:

{
  "code": 0,
  "msg": "ok",
  "data": { ... } | null,
  "request_id": "01J5XYZ..."
}

字段

字段类型说明
codei320 表示成功;非 0 是错误码,详见 错误码
msgstring人类可读的提示信息。code=0 时恒为 "ok"
dataany | null业务数据。成功时是端点定义的具体类型,错误时为 null
request_idstringULID,单调时间排序 + 随机。每个请求唯一,同时也是响应头 X-Request-Id

HTTP status code 与 envelope code 的关系

cr4sync 区分传输层失败业务层错误

类别HTTPenvelope.code何时
成功2000正常响应
业务错误200非 0参数校验失败 / 唯一约束冲突 / 上游 API 失败
鉴权失败401透传 / 1000头缺失 / Cloudreve 拒绝
权限不足4031000非 admin 访问 /admin/*
服务内部5003000 / 3001panic / IO 失败

业务错误一律 HTTP 200,靠 envelope.code 区分。客户端按 envelope.code 而不是 HTTP status 判错。

成功响应示例

{
  "code": 0,
  "msg": "ok",
  "data": {
    "version": "0.1.0",
    "user_id": "sub-alice",
    "is_admin": false,
    "email": "alice@example.com",
    "nickname": "Alice",
    "group_name": "User",
    "capabilities": ["sources", "storage", "migrate", "browse"]
  },
  "request_id": "01J5XYZABCDEFGHIJK"
}

错误响应示例

业务参数校验失败(HTTP 200):

{
  "code": 1000,
  "msg": "name must contain only ASCII letters / digits / _ / -",
  "data": null,
  "request_id": "01J5..."
}

鉴权失败(HTTP 401,透传 Cloudreve code):

{
  "code": 40301,
  "msg": "token expired",
  "data": null,
  "request_id": "01J5..."
}

非 admin 访问 admin 端点(HTTP 403):

{
  "code": 1000,
  "msg": "admin required",
  "data": null,
  "request_id": "01J5..."
}

request_id

  • middleware/request_id.rs 注入,所有路径都有(含 /health 白名单)。
  • 同时作为响应头 X-Request-Id 回写。
  • 写入 audit_log 表与日志 tracing span,可用于跨层追踪。

客户端实现要点

  1. 永远先读 envelope.code,不会根据 HTTP 200 / 4xx / 5xx 二分判错。
  2. request_id 写日志:把每次请求的 request_id 记到客户端日志,排障联调时给 server 端找审计/access log。
  3. null vs 缺省data 在错误时恒为 null;成功时若是空对象/数组,也是 {} / [],不会是 null
  4. 未来兼容:cr4sync 不保证 envelope 增字段时客户端能容忍——需宽松解析(额外字段忽略,缺字段 default)。