Skip to content

Instantly share code, notes, and snippets.

@scrogson
Created July 8, 2017 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scrogson/9785a4f9e5dbec4e22ac56d96ee1d584 to your computer and use it in GitHub Desktop.
Save scrogson/9785a4f9e5dbec4e22ac56d96ee1d584 to your computer and use it in GitHub Desktop.
Basic Rust HTTP Router
#![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