rust-web-utils 0.1.0

Lightweight web utilities: client IP & trusted proxies, bot/browser detection, unified JSON response, business timezone, auth cookies + CSRF, cron guards, Next.js static export hosting
Documentation
//! 统一 JSON 接口响应 `{ "code": int, "data": any, "msg": string }`。
//!
//! - `code`: 业务码, [`CODE_OK`] (200) 表示成功, 与 HTTP 状态解耦
//! - `data`: 业务数据; 序列化结果为 `null` 时 (如 `()`、`None`) 归一化为空对象 `{}`,
//!   永不返回 `null`; 列表用 `Vec` 表达, 空列表自然输出 `[]`
//! - `msg`: 提示信息, 对外一律英文短语
//!
//! 开启 `axum` feature 后 [`Response`] 实现 `IntoResponse`, handler 可直接返回:
//!
//! ```ignore
//! use rust_web_utils::resputil::{self, Response};
//!
//! async fn get_user() -> Response<User> {
//!     match load_user().await {
//!         Some(u) => resputil::ok(u),
//!         None => resputil::fail(40401, "user not found").erase(),
//!     }
//! }
//! ```
//!
//! 不用 Axum 时调用 [`Response::into_http`] 得到 `http::Response<Full<Bytes>>`。
//!
//! 完整文档: <https://rust-web-utils.czl.net/docs/resputil>

use std::borrow::Cow;

use bytes::Bytes;
use http::StatusCode;
use http::header::{CONTENT_TYPE, HeaderValue};
use http_body_util::Full;
use serde::Serialize;

/// 成功业务码
pub const CODE_OK: i32 = 200;

/// 统一 JSON 响应; 用 [`ok`] / [`ok_msg`] / [`fail`] / [`fail_status`] 构造
#[derive(Debug, Clone)]
pub struct Response<T> {
    status: StatusCode,
    code: i32,
    data: Option<T>,
    msg: Cow<'static, str>,
}

/// 成功响应 (HTTP 200, code 200, msg `success`)
pub fn ok<T: Serialize>(data: T) -> Response<T> {
    Response {
        status: StatusCode::OK,
        code: CODE_OK,
        data: Some(data),
        msg: Cow::Borrowed("success"),
    }
}

/// 带自定义提示的成功响应
pub fn ok_msg<T: Serialize>(data: T, msg: impl Into<Cow<'static, str>>) -> Response<T> {
    Response {
        status: StatusCode::OK,
        code: CODE_OK,
        data: Some(data),
        msg: msg.into(),
    }
}

/// 业务失败响应 (HTTP 200, data 为空对象); `code` 为业务错误码
pub fn fail(code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
    Response {
        status: StatusCode::OK,
        code,
        data: None,
        msg: msg.into(),
    }
}

/// 带 HTTP 状态码的失败响应 (data 为空对象), 用于 401 / 403 / 429 等需按 HTTP 状态拦截的场景;
/// 非法或 1xx 状态码矫正为 500, 避免 1xx 语义破坏 JSON 响应体
pub fn fail_status(http_status: u16, code: i32, msg: impl Into<Cow<'static, str>>) -> Response<()> {
    Response {
        status: sanitize_status(http_status),
        code,
        data: None,
        msg: msg.into(),
    }
}

fn sanitize_status(status: u16) -> StatusCode {
    if status < 200 {
        return StatusCode::INTERNAL_SERVER_ERROR;
    }
    StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}

impl<T> Response<T> {
    /// HTTP 状态码
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// 业务码
    pub fn code(&self) -> i32 {
        self.code
    }

    /// 提示信息
    pub fn msg(&self) -> &str {
        &self.msg
    }

    /// 覆盖 HTTP 状态码 (矫正规则同 [`fail_status`])
    pub fn with_status(mut self, http_status: u16) -> Self {
        self.status = sanitize_status(http_status);
        self
    }
}

impl Response<()> {
    /// 把无数据的失败响应转成任意 `Response<T>`, 便于同一 handler 的成功与失败分支返回同一类型
    pub fn erase<T>(self) -> Response<T> {
        Response {
            status: self.status,
            code: self.code,
            data: None,
            msg: self.msg,
        }
    }
}

impl<T: Serialize> Response<T> {
    /// 序列化为 JSON 字节; 失败时返回 `Err` (由 [`Response::into_http`] 降级为 500)
    pub fn to_json(&self) -> Result<Vec<u8>, serde_json::Error> {
        let data = match &self.data {
            Some(d) => serde_json::to_vec(d)?,
            None => Vec::new(),
        };
        // null 归一化为空对象
        let data: &[u8] = if data.is_empty() || data == b"null" {
            b"{}"
        } else {
            &data
        };
        let msg = serde_json::to_vec(self.msg.as_ref())?;

        let mut out = Vec::with_capacity(data.len() + msg.len() + 32);
        out.extend_from_slice(b"{\"code\":");
        out.extend_from_slice(self.code.to_string().as_bytes());
        out.extend_from_slice(b",\"data\":");
        out.extend_from_slice(data);
        out.extend_from_slice(b",\"msg\":");
        out.extend_from_slice(&msg);
        out.push(b'}');
        Ok(out)
    }

    /// 转为 `http::Response`; 序列化失败时降级为 HTTP 500 纯文本
    pub fn into_http(self) -> http::Response<Full<Bytes>> {
        match self.to_json() {
            Ok(body) => {
                let mut resp = http::Response::new(Full::new(Bytes::from(body)));
                *resp.status_mut() = self.status;
                resp.headers_mut().insert(
                    CONTENT_TYPE,
                    HeaderValue::from_static("application/json; charset=utf-8"),
                );
                resp
            }
            Err(_) => {
                let mut resp = http::Response::new(Full::new(Bytes::from_static(
                    b"internal error: response marshal failed\n",
                )));
                *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                resp.headers_mut()
                    .insert(CONTENT_TYPE, HeaderValue::from_static("text/plain; charset=utf-8"));
                resp
            }
        }
    }
}

#[cfg(feature = "axum")]
impl<T: Serialize> axum::response::IntoResponse for Response<T> {
    fn into_response(self) -> axum::response::Response {
        self.into_http().map(axum::body::Body::new)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use http_body_util::BodyExt;
    use serde::Serialize;

    use super::*;

    #[derive(Serialize)]
    #[serde(rename_all = "camelCase")]
    struct User {
        user_id: String,
        nick_name: Option<String>,
    }

    fn json<T: Serialize>(r: &Response<T>) -> String {
        String::from_utf8(r.to_json().unwrap()).unwrap()
    }

    #[test]
    fn normalizes_empty_data() {
        assert_eq!(json(&ok(())), r#"{"code":200,"data":{},"msg":"success"}"#);
        assert_eq!(json(&ok(None::<User>)), r#"{"code":200,"data":{},"msg":"success"}"#);
        assert_eq!(
            json(&ok(Vec::<User>::new())),
            r#"{"code":200,"data":[],"msg":"success"}"#
        );
        assert_eq!(
            json(&ok(HashMap::<String, i32>::new())),
            r#"{"code":200,"data":{},"msg":"success"}"#
        );
        assert_eq!(
            json(&fail(40401, "user not found")),
            r#"{"code":40401,"data":{},"msg":"user not found"}"#
        );
    }

    #[test]
    fn serializes_data_and_escapes_msg() {
        let u = User {
            user_id: "u_1".into(),
            nick_name: None,
        };
        assert_eq!(
            json(&ok_msg(u, "done \"ok\"")),
            r#"{"code":200,"data":{"userId":"u_1","nickName":null},"msg":"done \"ok\""}"#
        );
        assert_eq!(json(&ok(0)), r#"{"code":200,"data":0,"msg":"success"}"#);
        assert_eq!(json(&ok("")), r#"{"code":200,"data":"","msg":"success"}"#);
    }

    #[test]
    fn status_handling() {
        assert_eq!(fail(1, "x").status(), StatusCode::OK);
        assert_eq!(
            fail_status(429, 42900, "too many requests").status(),
            StatusCode::TOO_MANY_REQUESTS
        );
        assert_eq!(fail_status(101, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(fail_status(0, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(fail_status(1000, 1, "x").status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(ok(()).with_status(201).status(), StatusCode::CREATED);
        let erased: Response<User> = fail(40001, "bad").erase();
        assert_eq!((erased.code(), erased.msg()), (40001, "bad"));
    }

    struct Broken;
    impl Serialize for Broken {
        fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom("boom"))
        }
    }

    #[tokio::test]
    async fn into_http() {
        let resp = fail_status(401, 40100, "unauthorized").into_http();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(resp.headers()[CONTENT_TYPE], "application/json; charset=utf-8");
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(&body[..], br#"{"code":40100,"data":{},"msg":"unauthorized"}"#);

        let resp = ok(Broken).into_http();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}