Expand description
响应模块 — renderJson/renderSuccess/renderError + ApiResponse
对齐 PHP SzController::renderJson / renderSuccess / renderError。
响应格式:{ "code": 1, "msg": "", "data": {} }(字段顺序 code→msg→data)。
§PHP 对齐
| PHP 方法 | 行为 | Rust 等价 |
|---|---|---|
renderJson($code, $msg, $data) | 标准 JSON 响应 | ApiResponse::new + ApiResponse::into_response |
renderSuccess($msg, $data) | code=1 成功响应 | ApiResponse::success(Rust 参数顺序:data, msg) |
renderError($msg, $data) | code=0 失败响应 | ApiResponse::error |
renderError($msg, $data, $code) | 自定义错误码 | ApiResponse::error_with_code(Rust 参数顺序:code, msg, data) |
§字段顺序
严格遵循 PHP renderJson 的字段顺序:code → msg → data。
Rust 使用 serde_json::Map(preserve_order feature)来保证序列化顺序。
serde_json 默认启用 preserve_order,依赖 indexmap。
§Content-Type
所有响应自动附带 Content-Type: application/json; charset=utf-8。
§HTTP 状态码
业务成功(code=1)和业务失败(code=0)都返回 HTTP 200(对齐 PHP 行为);
异常场景(500/404)由 1.9 错误处理模块处理。
Structs§
- ApiResponse
- 标准 API 响应结构体
- Json
Response - JSON 响应包装器(项目主策略:默认 JSON 返回)
- Jsonp
Response - JSONP 响应包装器
Enums§
- Default
Response Type - 默认响应类型策略(对齐 PHP
autoResponse+ 项目主策略扩展)
Functions§
- auto_
respond - 自动响应(对齐 PHP
Dispatch::autoResponse()) - is_
json_ request - 检查请求是否为 JSON 请求(对齐 PHP
Request::isJson()) - is_
valid_ jsonp_ callback - 校验 JSONP 回调函数名是否合法
- render_
error - 构建错误响应
- render_
error_ with_ code - 构建带自定义错误码的错误响应
- render_
json - 直接构建标准 JSON 响应(无需创建 ApiResponse 实例)
- render_
success - 构建成功响应
- respond
- 默认 JSON 响应(项目主策略:前后端分离)
- respond_
html - HTML 响应(兜底场景:模板渲染、PDF/Excel 导出)
- respond_
jsonp - 构建 JSONP 响应(对齐 PHP
json()+'jsonp'类型) - respond_
text - 纯文本响应(Content-Type: text/plain; charset=utf-8)