gotham/middleware/
timer.rs1use crate::handler::HandlerFuture;
3use crate::helpers::http::header::X_RUNTIME_DURATION;
4use crate::helpers::timing::Timer;
5use crate::middleware::{Middleware, NewMiddleware};
6use crate::state::State;
7use futures_util::future::{self, FutureExt, TryFutureExt};
8use std::pin::Pin;
9
10#[derive(Clone)]
15pub struct RequestTimer;
16
17impl Middleware for RequestTimer {
19 fn call<Chain>(self, state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
21 where
22 Chain: FnOnce(State) -> Pin<Box<HandlerFuture>>,
23 {
24 let timer = Timer::new();
26
27 let f = chain(state).and_then(move |(state, mut response)| {
29 response.headers_mut().insert(
31 X_RUNTIME_DURATION,
32 timer.elapsed().to_string().parse().unwrap(),
33 );
34
35 future::ok((state, response))
36 });
37
38 f.boxed()
39 }
40}
41
42impl NewMiddleware for RequestTimer {
44 type Instance = Self;
45
46 fn new_middleware(&self) -> anyhow::Result<Self::Instance> {
48 Ok(self.clone())
49 }
50}