跳转到内容
彼岸论坛
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[Rust] [actix-web]感觉这么写好丑呀,求推荐新写法


已推荐帖子

发表于
```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());
}
}
}

```
  • 游客注册

    游客注册

  • 会员

    没有会员可显示

  • 最新的状态更新

    没有最新的状态更新
  • 最近查看

    • 没有会员查看此页面.
×
×
  • 创建新的...