rust actix-web 动态路由

2024-11-23  本文已影响0人  国服最坑开发

1、效果

在 actix-web 中,可以通过环境变量在运行时决定路由的处理逻辑。

use actix_web::{web, App, HttpServer, Responder};
use std::env;

async fn handler_one() -> impl Responder {
    "This is handler one"
}

async fn handler_two() -> impl Responder {
    "This is handler two"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 读取环境变量,默认为 "one"
    let handler_choice = env::var("HANDLER_CHOICE").unwrap_or_else(|_| "one".to_string());

    // 根据环境变量选择处理器
    let handler = match handler_choice.as_str() {
        "two" => web::post().to(handler_two),
        _ => web::post().to(handler_one),
    };

    // 启动服务
    HttpServer::new(move || {
        App::new()
            .service(
                web::resource("/your_uri")
                    .route(handler.clone()) // 使用动态选择的 handler
            )
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

上一篇 下一篇

猜你喜欢

热点阅读