Created
July 8, 2017 21:54
-
-
Save scrogson/9785a4f9e5dbec4e22ac56d96ee1d584 to your computer and use it in GitHub Desktop.
Basic Rust HTTP Router
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
#![allow(dead_code)] | |
use std::collections::HashMap; | |
type Headers = HashMap<String, String>; | |
type BoxedCallback = Box<Fn(Conn) -> Conn>; | |
#[derive(Default)] | |
struct Request { | |
method: String, | |
url: String, | |
headers: Headers, | |
body: Vec<u8>, | |
} | |
#[derive(Default)] | |
struct Response { | |
status: u32, | |
headers: Headers, | |
body: Vec<u8>, | |
} | |
#[derive(Default)] | |
struct Conn { | |
pub request: Request, | |
pub response: Response, | |
} | |
struct Router { | |
routes: HashMap<String, BoxedCallback>, | |
} | |
impl Router { | |
fn new() -> Router { | |
Router { routes: HashMap::new() } | |
} | |
fn add_route<C>(&mut self, url: &str, callback: C) | |
where C: Fn(Conn) -> Conn + 'static | |
{ | |
self.routes.insert(url.to_string(), Box::new(callback)); | |
} | |
fn handle_request(&self, conn: Conn) -> Conn { | |
match self.routes.get(&conn.request.url) { | |
None => Conn::default(), | |
Some(callback) => callback(conn) | |
} | |
} | |
} | |
fn main() { | |
let mut router = Router::new(); | |
router.add_route("/", |conn| { | |
println!("Serving /"); | |
conn | |
}); | |
router.add_route("/hello", |conn| { | |
println!("Serving /hello"); | |
conn | |
}); | |
let mut conn = Conn::default(); | |
conn.request.url = "/hello".to_string(); | |
router.handle_request(conn); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment