Last active
October 23, 2016 21:59
-
-
Save JohnMurray/b9995acacb5e6ba2827ad8f2228d7f1c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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