Skip to main content

rust_web_utils/
resputil.rs

1//! 统一 JSON 接口响应 `{ "code": int, "data": any, "msg": string }`。
2//!
3//! - `code`: 业务码, [`CODE_OK`] (200) 表示成功, 与 HTTP 状态解耦
4//! - `data`: 业务数据; 序列化结果为 `null` 时 (如 `()`、`None`) 归一化为空对象 `{}`,
5//!   永不返回 `null`; 列表用 `Vec` 表达, 空列表自然输出 `[]`
6//! - `msg`: 提示信息, 对外一律英文短语
7//!
8//! 开启 `axum` feature 后 [`Response`] 实现 `IntoResponse`, handler 可直接返回:
9//!
10//! ```ignore
11//! use rust_web_utils::resputil::{self, Response};
12//!
13//! async fn get_user() -> Response<User> {
14//!     match load_user().await {
15//!         Some(u) => resputil::ok(u),
16//!         None => resputil::fail(40401, "user not found").erase(),
17//!     }
18//! }
19//! ```
20//!
21//! 不用 Axum 时调用 [`Response::into_http`] 得到 `http::Response<Full<Bytes>>`。
22//!
23//! 完整文档: <https://rust-web-utils.czl.net/docs/resputil>
24
25use std::borrow::Cow;
26
27use bytes::Bytes;
28use http::StatusCode;
29use http::header::{CONTENT_TYPE, HeaderValue};
30use http_body_util::Full;
31use serde::Serialize;
32
33/// 成功业务码
34pub const CODE_OK: i32 = 200;
35
36/// 统一 JSON 响应; 用 [`ok`] / [`ok_msg`] / [`fail`] / [`fail_status`] 构造
37#[derive(Debug, Clone)]
38pub struct Response<T> {
39    status: StatusCode,
40    code: i32,
41    data: Option<T>,
42    msg: Cow<'static, str>,
43}
44
45/// 成功响应 (HTTP 200, code 200, msg `success`)
46pub fn ok<T: Serialize>(data: T) -> Response<T> {
47    Response {
48        status: StatusCode::OK,
49        code: CODE_OK,
50        data: Some(data),
51        msg: Cow::Borrowed("success"),
52    }
53}
54
55/// 带自定义提示的成功响应
56pub fn ok_msg<T: Serialize>(data: T, msg: impl Into<Cow<'static, str>>) -> Response<T> {
57    Response {
58        status: StatusCode::OK,
59        code: CODE_OK,
60        data: Some(data),
61        msg: msg.into(),
62    }
63}
64
65/// 业务失败响应 (HTTP 200, data 为空对象); `code` 为业务错误码
66pub fn fail(code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
67    Response {
68        status: StatusCode::OK,
69        code,
70        data: None,
71        msg: msg.into(),
72    }
73}
74
75/// 带 HTTP 状态码的失败响应 (data 为空对象), 用于 401 / 403 / 429 等需按 HTTP 状态拦截的场景;
76/// 非法或 1xx 状态码矫正为 500, 避免 1xx 语义破坏 JSON 响应体
77pub fn fail_status(http_status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
78    Response {
79        status: sanitize_status(http_status),
80        code,
81        data: None,
82        msg: msg.into(),
83    }
84}
85
86fn sanitize_status(status: u16) -> StatusCode {
87    if status < 200 {
88        return StatusCode::INTERNAL_SERVER_ERROR;
89    }
90    StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
91}
92
93impl<T> Response<T> {
94    /// HTTP 状态码
95    pub fn status(&self) -> StatusCode {
96        self.status
97    }
98
99    /// 业务码
100    pub fn code(&self) -> i32 {
101        self.code
102    }
103
104    /// 提示信息
105    pub fn msg(&self) -> &str {
106        &self.msg
107    }
108
109    /// 覆盖 HTTP 状态码 (矫正规则同 [`fail_status`])
110    pub fn with_status(mut self, http_status: u16) -> Self {
111        self.status = sanitize_status(http_status);
112        self
113    }
114}
115
116impl Response<()> {
117    /// 把无数据的失败响应转成任意 `Response<T>`, 便于同一 handler 的成功与失败分支返回同一类型
118    pub fn erase<T>(self) -> Response<T> {
119        Response {
120            status: self.status,
121            code: self.code,
122            data: None,
123            msg: self.msg,
124        }
125    }
126}
127
128impl<T: Serialize> Response<T> {
129    /// 序列化为 JSON 字节; 失败时返回 `Err` (由 [`Response::into_http`] 降级为 500)
130    pub fn to_json(&self) -> Result<Vec<u8>, serde_json::Error> {
131        let data = match &self.data {
132            Some(d) => serde_json::to_vec(d)?,
133            None => Vec::new(),
134        };
135        // null 归一化为空对象
136        let data: &[u8] = if data.is_empty() || data == b"null" {
137            b"{}"
138        } else {
139            &data
140        };
141        let msg = serde_json::to_vec(self.msg.as_ref())?;
142
143        let mut out = Vec::with_capacity(data.len() + msg.len() + 32);
144        out.extend_from_slice(b"{\"code\":");
145        out.extend_from_slice(self.code.to_string().as_bytes());
146        out.extend_from_slice(b",\"data\":");
147        out.extend_from_slice(data);
148        out.extend_from_slice(b",\"msg\":");
149        out.extend_from_slice(&msg);
150        out.push(b'}');
151        Ok(out)
152    }
153
154    /// 转为 `http::Response`; 序列化失败时降级为 HTTP 500 纯文本
155    pub fn into_http(self) -> http::Response<Full<Bytes>> {
156        match self.to_json() {
157            Ok(body) => {
158                let mut resp = http::Response::new(Full::new(Bytes::from(body)));
159                *resp.status_mut() = self.status;
160                resp.headers_mut().insert(
161                    CONTENT_TYPE,
162                    HeaderValue::from_static("application/json; charset=utf-8"),
163                );
164                resp
165            }
166            Err(_) => {
167                let mut resp = http::Response::new(Full::new(Bytes::from_static(
168                    b"internal error: response marshal failed\n",
169                )));
170                *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
171                resp.headers_mut()
172                    .insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
173                resp
174            }
175        }
176    }
177}
178
179#[cfg(feature = "axum")]
180impl<T: Serialize> axum::response::IntoResponse for Response<T> {
181    fn into_response(self) -> axum::response::Response {
182        self.into_http().map(axum::body::Body::new)
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use std::collections::HashMap;
189
190    use http_body_util::BodyExt;
191    use serde::Serialize;
192
193    use super::*;
194
195    #[derive(Serialize)]
196    #[serde(rename_all = "camelCase")]
197    struct User {
198        user_id: String,
199        nick_name: Option<String>,
200    }
201
202    fn json<T: Serialize>(r: &Response<T>) -> String {
203        String::from_utf8(r.to_json().unwrap()).unwrap()
204    }
205
206    #[test]
207    fn normalizes_empty_data() {
208        assert_eq!(json(&ok(())), r#"{"code":200,"data":{},"msg":"success"}"#);
209        assert_eq!(json(&ok(None::<User>)), r#"{"code":200,"data":{},"msg":"success"}"#);
210        assert_eq!(
211            json(&ok(Vec::<User>::new())),
212            r#"{"code":200,"data":[],"msg":"success"}"#
213        );
214        assert_eq!(
215            json(&ok(HashMap::<String, i32>::new())),
216            r#"{"code":200,"data":{},"msg":"success"}"#
217        );
218        assert_eq!(
219            json(&fail(40401, "user not found")),
220            r#"{"code":40401,"data":{},"msg":"user not found"}"#
221        );
222    }
223
224    #[test]
225    fn serializes_data_and_escapes_msg() {
226        let u = User {
227            user_id: "u_1".into(),
228            nick_name: None,
229        };
230        assert_eq!(
231            json(&ok_msg(u, "done \"ok\"")),
232            r#"{"code":200,"data":{"userId":"u_1","nickName":null},"msg":"done \"ok\""}"#
233        );
234        assert_eq!(json(&ok(0)), r#"{"code":200,"data":0,"msg":"success"}"#);
235        assert_eq!(json(&ok("")), r#"{"code":200,"data":"","msg":"success"}"#);
236    }
237
238    #[test]
239    fn status_handling() {
240        assert_eq!(fail(1, "x").status(), StatusCode::OK);
241        assert_eq!(
242            fail_status(429, 42900, "too many requests").status(),
243            StatusCode::TOO_MANY_REQUESTS
244        );
245        assert_eq!(fail_status(101, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
246        assert_eq!(fail_status(0, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
247        assert_eq!(fail_status(1000, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
248        assert_eq!(ok(()).with_status(201).status(), StatusCode::CREATED);
249        let erased: Response<User> = fail(40001, "bad").erase();
250        assert_eq!((erased.code(), erased.msg()), (40001, "bad"));
251    }
252
253    struct Broken;
254    impl Serialize for Broken {
255        fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
256            Err(serde::ser::Error::custom("boom"))
257        }
258    }
259
260    #[tokio::test]
261    async fn into_http() {
262        let resp = fail_status(401, 40100, "unauthorized").into_http();
263        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
264        assert_eq!(resp.headers()[CONTENT_TYPE], "application/json; charset=utf-8");
265        let body = resp.into_body().collect().await.unwrap().to_bytes();
266        assert_eq!(&body[..], br#"{"code":40100,"data":{},"msg":"unauthorized"}"#);
267
268        let resp = ok(Broken).into_http();
269        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
270    }
271}