rust - actix 3 Application ( scope 路由, 静态变量, 全局线程共享变量, virtual host 以及配置 config)
访问量: 1514
参考:https://actix.rs/docs/application/
1. 增加 /app 这样的scope , 来访问路由 ( 等同于 rails中的 namespace route)
创建新项目, 修改src/main.rs:
use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use actix_web::get; async fn hi() -> impl Responder { HttpResponse::Ok().body("hello, 3") } #[actix_rt::main] async fn main() -> std::io::Result<()> { HttpServer::new( || { App::new() .service( web::scope("/app").route("/say_hi.page", web::get().to(hi)), ) }) .bind("127.0.0.1:8088")? .run() .await }
在浏览器中访问 http://localhost:8088/app/say_hi.page 就可以了。
2. 使用全局静态变量(特别适合做配置项?)
修改src/main.rs:
use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use std::sync::Mutex; // 需要定义一个这样的struct struct AppState { today_string: String } async fn show_state(data: web::Data) -> impl Responder { let today_string = &data.today_string; //HttpResponse::Ok().body("hello, index") format!("hihihi {}", today_string) } #[actix_rt::main] async fn main() -> std::io::Result<()> { HttpServer::new( || { App::new() // 初始化state .data(AppState { today_string: String::from("2020-5-16") }) .route("/show_state", web::get().to(show_state)) }) .bind("127.0.0.1:8088")? .run() .await }
打开浏览器,访问:
http://localhost:8088/show_state
就可以看到了hihihi 2020-5-16
可以注意到, actix中的action , 默认最后一行的是返回内容。 可以认为,下面三行代码是等价的:
async fn show_state(data: web::Data) -> impl Responder { let today_string = &data.today_string; // 完整形式1 //HttpResponse::Ok().body("hello, index") // 省略形式1: 直接返回字符串,作为http response body, code = 200 //format!("hihihi {}", today_string) // 省略形式2 直接返回字符串 //"haisdfasdfasdf" // 最完整形式: return, 啥的一个都不能少。 return HttpResponse::Ok().body(format!("hello, today_string is : {}", today_string)) }