[actix-web]感觉这么写好丑呀,求推荐新写法 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
RedBeanIce
V2EX    Rust

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

  •  
  •   RedBeanIce 2024-07-26 08:42:58 +08:00 2445 次点击
    这是一个创建于 516 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ```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  
       2024-07-26 08:50:21 +08:00   1
    好吧,一直用 axum 的路过。。。
    dyc12389
        2
    dyc12389  
       2024-07-26 09:44:05 +08:00   1
    定义一个 Error 的枚举,derive(this_error::Error)

    impl actix_web::ResponseError for Error {
    }

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

    正常的返回就用你封装的 response 就行
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     3202 人在线   最高记录 6679     &nbp; Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 26ms UTC 10:55 PVG 18:55 LAX 02:55 JFK 05:55
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86