Skip to main content

wae_https/response/
mod.rs

1//! HTTP 响应模块
2//!
3//! 提供统一的响应处理工具。
4
5use axum::{
6    body::Body,
7    http::{Response, StatusCode, header},
8    response::IntoResponse,
9};
10use serde::Serialize;
11
12use crate::ApiResponse;
13
14/// JSON 响应构建器
15pub struct JsonResponse;
16
17impl JsonResponse {
18    /// 返回成功响应
19    pub fn success<T: Serialize>(data: T) -> Response<Body> {
20        ApiResponse::success(data).into_response()
21    }
22
23    /// 返回错误响应
24    pub fn error(code: impl Into<String>, message: impl Into<String>) -> Response<Body> {
25        ApiResponse::<()>::error(code, message).into_response()
26    }
27
28    /// 返回 404 错误
29    pub fn not_found(message: impl Into<String>) -> Response<Body> {
30        let body = ApiResponse::<()>::error("NOT_FOUND", message);
31        Response::builder()
32            .status(StatusCode::NOT_FOUND)
33            .header(header::CONTENT_TYPE, "application/json")
34            .body(Body::from(serde_json::to_string(&body).unwrap_or_default()))
35            .unwrap()
36    }
37
38    /// 返回 500 错误
39    pub fn internal_error(message: impl Into<String>) -> Response<Body> {
40        let body = ApiResponse::<()>::error("INTERNAL_ERROR", message);
41        Response::builder()
42            .status(StatusCode::INTERNAL_SERVER_ERROR)
43            .header(header::CONTENT_TYPE, "application/json")
44            .body(Body::from(serde_json::to_string(&body).unwrap_or_default()))
45            .unwrap()
46    }
47}