扩展可以存储应用程序级别的状态或配置,并可通过请求处理程序获取。下面是使用扩展存储全局配置的示例:
use std::collections::HashMap;
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
struct AppConfig {
name: String,
settings: HashMap,
}
fn index(config: web::Data, req: HttpRequest) -> HttpResponse {
let response_body = format!("Hello, {}!", config.name);
HttpResponse::Ok().body(response_body)
}
fn main() -> std::io::Result<()> {
let config = AppConfig {
name: "Actix".to_owned(),
settings: [
("version".to_owned(), "0.7.19".to_owned()),
("author".to_owned(), "Actix Contributors".to_owned()),
].iter().cloned().collect(),
};
HttpServer::new(move || {
App::new()
.data(config.clone())
.route("/", web::get().to(index))
})
.bind("127.0.0.1:8080")?
.run()
}
在此示例中,AppConfig 结构体存储应用程序的全局配置。在 main() 中创建了 config 的实例,并将其转移到 HttpServer::new() 方法中的闭包中,以便在构造 App 时使用。App::data() 方法用于添加存储在 Data 中的 AppConfig 实例,以供 index() 处理程序使用。
在 index() 处理程序中,我们使用 web::Data 类型的参数获取存储在扩展中的全局配置。然后,我们可以从 config 中检索数据,并为请求创建相应。在此示例中,我们使用了 config.name 进行问候。