Iron面向中间件的 Web 框架
Iron ,一个用 Rust 编写的可扩展的、并发的 Web 框架。
Iron 是一个快速、灵活的面向中间件的服务器框架,它提供了小巧但健壮的基础以创建复杂的应用和 RESTful APIs。Iron 没有和中间件捆绑在一起,任何东西都是可以拖拽的(drag-and-drop),这允许你天马行空地进行模块设置。
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(); }
评论