跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

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

```

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.