-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.rs
36 lines (29 loc) · 1023 Bytes
/
time.rs
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
32
33
34
35
36
extern crate iron;
extern crate time;
use iron::prelude::*;
use iron::{BeforeMiddleware, AfterMiddleware, typemap};
use time::precise_time_ns;
struct ResponseTime;
impl typemap::Key for ResponseTime { type Value = u64; }
impl BeforeMiddleware for ResponseTime {
fn before(&self, req: &mut Request) -> IronResult<()> {
req.extensions.insert::<ResponseTime>(precise_time_ns());
Ok(())
}
}
impl AfterMiddleware for ResponseTime {
fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> {
let delta = precise_time_ns() - *req.extensions.get::<ResponseTime>().unwrap();
println!("Request took: {} ms", (delta as f64) / 1000000.0);
Ok(res)
}
}
fn hello_world(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((iron::status::Ok, "Hello World")))
}
fn main() {
let mut chain = Chain::new(hello_world);
chain.link_before(ResponseTime);
chain.link_after(ResponseTime);
Iron::new(chain).http("localhost:3000").unwrap();
}