Routing for server


Hi all.
I’m working through creating server on Rust, and got a question, i have next example:
struct Router {
routes: HashMap<String, Box>

impl Router {

fn new() -> Self {
    Router {
        routes: HashMap::new()

fn add_route<H>(&mut self, path: String, handler: H) where H: Handler {
    self.routes.insert(path, Box::new(handler));

impl Handler for Router {
fn handle(&self, req: &mut Request) -> IronResult {
match self.routes.get(&req.url.path().join("/")) {
Some(handler2) => handler2.handle(req),
None => Ok(Response::with(status::NotFound))
fn main() {
let mut router = Router::new();

router.add_route(“hello_habrahabr”.to_string(), |_: &mut Request| {
Ok(Response::with((status::Ok, “Hello Loo Maclin!\n”)))

router.add_route(“hello_habrahabr/again”.to_string(), |_: &mut Request| {
Ok(Response::with((status::Ok, “Ты повторяешься!\n”)))
As i understood handler2 in this part of code represents Box<T:Handle> , right? But where is the definition of
handle(&mut Request) for it ???
Another thing i figured out is that we are Boxing a closure in add_route(&mut self, path: String, handler: H) where H: Handler{}
but how is it called out?I guess that the only way for it to be called is that it is called exactly in here:
Some(handler2) => handler2.handle(req),


It’s provided by iron itself:

Please format code snippets in your posts.


So the closure that we are Boxing in add_rout() basicaly is the handler of the Request for the server, and handle(rec) method just calls it automatically as defined in Rust?


It’s handler for the specified route, yes. Right above the lines I linked to earlier is iron's implementation of Handler for a closure, which ties the pieces together: a (unboxed) closure is a Handler, a Box<Handler> is a Handler, and these two allow a boxed closure to be a handler.