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
}