use std::collections::HashMap; use json::JsonValue; use std::future::Future; use futures::future::BoxFuture; pub trait Handler: Send + Sync + 'static { fn handle(&self, _: JsonValue) -> BoxFuture<'static, ()>; } impl Handler for C where C: Send + Sync + 'static + Fn(JsonValue) -> F, F: Future + 'static + Send { fn handle(&self, req: JsonValue) -> BoxFuture<'static, ()> { Box::pin((*self)(req)) } } pub struct UpdateRouter { router: HashMap>, rt: tokio::runtime::Handle, } impl UpdateRouter { pub fn new(rt: tokio::runtime::Handle) -> Self { Self { router: HashMap::new(), rt: rt } } pub fn add_handler(&mut self, update_type: &str, handler: H) { self.router.insert(update_type.to_owned(), Box::new(handler)); } pub fn dispatch(&self, update: JsonValue) { let update_type: &str = update["@type"].as_str().unwrap(); self.router.get(update_type) .and_then(|handler| { self.rt.spawn(handler.handle(update)); Some(()) }) .or_else(|| { println!("handler not found"); Some(()) }); } }