Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active October 23, 2016 21:59
Show Gist options
  • Save JohnMurray/b9995acacb5e6ba2827ad8f2228d7f1c to your computer and use it in GitHub Desktop.
Save JohnMurray/b9995acacb5e6ba2827ad8f2228d7f1c to your computer and use it in GitHub Desktop.
extern crate iron;
extern crate mysql;
use iron::prelude::*;
use iron::status;
use iron::{Handler};
struct Router {
routes: HashMap<String, Box<Handler>>
}
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<Response> {
match self.routes.get(&req.url.path().join("/")) {
Some(handler) => handler.handle(req),
None => Ok(Response::with(status::NotFound))
}
}
}
fn main() {
let pool = mysql::Pool::new("mysql://root:password@localhost:3306/some_db").unwrap();
let mut router = Router::new()
router.add_route("hello".to_string(), |_: &mut Request| {
// use `pool` to read info from DB
// error: closure may outlive the current function, but it borrows `pool`, which is owned by the current function [E0373]
Ok(Response::with((status::Ok, "some data retrieved from DB")))
});
Iron::new(router).http("localhost:3000").unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment