rust-web-utils

统一响应 (resputil)

统一 JSON 响应 { code, data, msg }, 空数据永不返回 null

结构

{ "code": 200, "data": {}, "msg": "success" }
  • code: 业务码, CODE_OK (200) 为成功, 与 HTTP 状态解耦
  • data: 序列化结果为 null 时 (如 ()、None) 归一为 {}; 列表用 Vec, 空列表输出 []
  • msg: 对外一律英文短语; UI 展示人话时带上 code

用法

use rust_web_utils::resputil::{self, Response};

async fn get_user(Path(id): Path<String>) -> Response<UserView> {
    match service::user::find(&id).await {
        Ok(Some(u)) => resputil::ok(u.into()),
        Ok(None) => resputil::fail(40401, "user not found").erase(),
        Err(_) => resputil::fail_status(500, 50000, "internal error").erase(),
    }
}
构造HTTP 状态说明
ok(data)200code 200, msg success
ok_msg(data, msg)200自定义提示
fail(code, msg)200业务失败, data 为 {}
fail_status(status, code, msg)自定义401 / 403 / 429 等需网关或前端拦截器按 HTTP 状态处理的场景
  • .erase() 把无数据的失败响应转成任意 Response<T>, 同一 handler 的成功与失败分支返回同一类型
  • .with_status(u16) 覆盖 HTTP 状态; 1xx 与非法状态码矫正为 500
  • 开启 axum feature 后 Response<T> 实现 IntoResponse; 不用 Axum 时 .into_http() 得到 http::Response<Full<Bytes>>, .to_json() 得到字节
  • 序列化失败降级为 HTTP 500 纯文本

错误映射

领域错误用 thiserror 枚举定义, 在一处实现到 Response 的映射 (如为错误类型实现 IntoResponse 并内部调用 fail / fail_status)。上游原始码、SQL 与调用栈只进日志, 不进 msg。