Created
June 20, 2021 17:39
-
-
Save mooreniemi/99b440bfbf1d77159f3d648f3f6842c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![deny(warnings)] | |
use std::{collections::HashMap, convert::Infallible, sync::Arc}; | |
use tokio::sync::RwLock; | |
use warp::{Filter, Rejection}; | |
fn with_store( | |
store: Arc<RwLock<HashMap<String, u64>>>, | |
) -> impl Filter<Extract = (Arc<RwLock<HashMap<String, u64>>>,), Error = Infallible> + Clone { | |
warp::any().map(move || store.clone()) | |
} | |
async fn inc_path<T>(path: T, store: Arc<RwLock<HashMap<String, u64>>>) -> Result<(), Rejection> | |
where | |
T: Send + Sync + ToString, | |
{ | |
println!("before filter: {:?}", path.to_string()); | |
let mut s = store.write().await; | |
let c = s.entry(path.to_string()).or_insert(0); | |
*c += 1; | |
let res: Result<(), Rejection> = Ok(()); | |
res | |
} | |
fn inc_by_path_wrapper<F, T>( | |
filter: F, | |
store: Arc<RwLock<HashMap<String, u64>>>, | |
) -> impl Filter<Extract = (T,)> + Clone + Send + Sync + 'static | |
where | |
F: Filter<Extract = (T,), Error = Infallible> + Clone + Send + Sync + 'static, | |
F::Extract: warp::Reply, | |
T: Send + Sync + 'static + ToString, | |
{ | |
println!("called wrapper... (init)"); | |
warp::path::param() | |
.and(with_store(store)) | |
.and_then(inc_path) | |
.untuple_one() | |
.and(filter) | |
} | |
#[tokio::main] | |
async fn main() { | |
let h = Arc::new(RwLock::new(HashMap::new())); | |
// Match any request and return hello world! | |
let routes = warp::any() | |
.map(|| "hello world") | |
.boxed() | |
.recover(|_err| async { Ok("recovered") }) | |
.unify() | |
// wrap the filter with hello_wrapper | |
.with(warp::wrap_fn(move |f| inc_by_path_wrapper(f, h.clone()))); | |
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await; | |
} |
Author
mooreniemi
commented
Jun 20, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment