-
Hi all, I like to use the manual approach when it comes to defining my http services and am trying to inject variables/shared state into my handler functions using the age-old property injection approach. I am struggling to do this with Actix - is there an ergonomic way to achieve what I'm trying to do? #[tokio::main]
async fn main() -> std::io::Result<()> {
let shared_state = Arc::new(RwLock::new(42)); // Pass this into my handlers
HttpServer::new(move || {
let mut app = App::new();
app = app.route("/", web::get().to(handler_root(shared_state.clone()))); // invalid type for 'handler_root'
app
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
// I assume this is an invalid type
pub type HandlerFunc = Box<dyn Fn() -> Pin<Box<dyn Future<Output = HttpResponse>>>>;
// Factory function that returns my handler
fn handler_root(shared_state: Arc<RwLock<usize>>) -> HandlerFunc {
Box::new(move || Box::pin({
let shared_state = shared_state.clone();
async move {
HttpResponse::Ok().body(format!("Hey there! {}", shared_state.read().await))
}
}))
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
State is not passed to handlers like that. You can read about how to set up shared mutable state in the guide: https://actix.rs/docs/application#shared-mutable-state Also see the docs for |
Beta Was this translation helpful? Give feedback.
State is not passed to handlers like that. You can read about how to set up shared mutable state in the guide: https://actix.rs/docs/application#shared-mutable-state
Also see the docs for
App::app_data()
and the links through toData<T>
's docs.