1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
use async_std::future; use std::time::{Duration, SystemTime}; use tide::{Middleware, Next, Request, Response}; #[derive(Clone, Debug)] pub struct DelayMiddleware { expected_duration: Duration, } impl DelayMiddleware { pub fn new(expected_duration: Duration) -> Self { Self { expected_duration } } } #[tide::utils::async_trait] impl<State: Clone + Send + Sync + 'static> Middleware<State> for DelayMiddleware { async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> tide::Result { let time = SystemTime::now(); let res: Response = next.run(req).await; if let Ok(elapsed_duration) = time.elapsed() { if let Some(remaining_duration) = self.expected_duration.checked_sub(elapsed_duration) { let _ = future::timeout(remaining_duration, future::pending::<()>()).await; } } Ok(res) } }