struct AppState {
my_big_heavy_object: HeavyObject,
}
HeavyObject
HttpRequest<AppState>
index
HttpRequest
state
fn index(req: HttpRequest<AppState>) -> HttpResponse {
let result = do_something_with(req.state.my_big_heavy_object);
HttpResponse::Ok()
.content_type("application/json")
.body(result)
}
当建立
App
with_state
构造函数而不是
new
server::new(|| {
let app_state = AppState { my_big_heavy_object: compute_big_heavy_object() };
App::with_state(app_state).resource("/", |r| r.f(index))
})
.bind("127.0.0.1:8088")
.unwrap()
.run();
请注意,假定应用程序状态是不可变的。听起来你不需要任何处理程序来改变它,但是如果你这样做了,你就必须使用
Cell
RefCell