V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
RedBeanIce
V2EX  ›  Rust

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

  •  
  •   RedBeanIce · 44 天前 · 1451 次点击
    这是一个创建于 44 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ```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());
    }
    }
    }

    ```
    2 条回复    2024-07-26 09:44:05 +08:00
    lsk569937453
        1
    lsk569937453  
       44 天前   ❤️ 1
    好吧,一直用 axum 的路过。。。
    dyc12389
        2
    dyc12389  
       44 天前   ❤️ 1
    定义一个 Error 的枚举,derive(this_error::Error)

    impl actix_web::ResponseError for Error {
    }

    所有路由的 handler 返回都可以用 actix_web::Result
    这样就把这个框架里的 error 统一起来了

    正常的返回就用你封装的 response 就行
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2497 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 03:06 · PVG 11:06 · LAX 20:06 · JFK 23:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.