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

[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());
}
}
}

```
意见的链接
分享到其他网站

加入讨论

您现在可以发表并稍后注册. 如果您是会员,请现在登录来参与讨论.

游客
回复主题...

×   粘贴为富文本.   粘贴为纯文本来代替

  只允许使用75个表情符号.

×   您的链接已自动嵌入.   显示为链接来代替

×   您之前的内容已恢复.   清除编辑器

×   您无法直接粘贴图片.要从网址上传或插入图片.

  • 游客注册

    游客注册

  • 会员

    没有会员可显示

  • 最新的状态更新

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

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