```rust
use actix_http::header::TryIntoHeaderPair;
use actix_http::StatusCode;
use actix_web::http::header::ContentType;
use actix_web::HttpResponse;
use serde::{Deserialize, Serialize};
// 自定义 Response
#[derive(Deserialize, Serialize, Debug)]
pub(crate) struct R<T> {
pub(crate) code: i32,
pub(crate) msg: String,
pub(crate) data: Option<T>,
}
// 在 R<T> 结构体附近定义辅助方法
impl<T> R<T>
where
T: Serialize,
{
// 创建成功的响应
pub fn success(data: T) -> HttpResponse {
let r: R<T> = R {
code: StatusCode::OK.as_u16() as i32,
msg: "请求成功".to_string(),
data: Some(data),
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}
// 创建失败的响应
pub fn err() -> HttpResponse {
let r: R<()> = R {
code: StatusCode::INTERNAL_SERVER_ERROR.as_u16() as i32,
msg: "服务器异常".to_string(),
data: None,
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}
// 创建失败的响应
pub fn err_msg(msg: String) -> HttpResponse {
let r: R<()> = R {
code: StatusCode::INTERNAL_SERVER_ERROR.as_u16() as i32,
msg,
data: None,
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}
// 创建自定义状态码的响应
pub fn custom(code: i32, msg: String, data: Option<T>) -> HttpResponse {
let r: R<T> = R {
code,
msg,
data,
};
HttpResponse::build(StatusCode::OK)
.insert_header(ContentType::json())
.body(serde_json::to_string(&r).unwrap())
}
}
```
```rust
#[post("/api/v1/deposits/list")]
async fn deposits_list(pool: web::Data<PgPool>) -> impl Responder {
let list = Deposit::list(&pool).await;
match list {
Ok(list) => R::success(list),
Err(e) => {
// 处理错误,例如返回一个错误响应
eprintln!("Error querying deposits: {:?}", e);
// 假设 R::error 是你用来处理错误响应的方法
return R::<String>::err_msg("Failed to fetch deposits".to_string());
}
}
}
```