Skip to content

Instantly share code, notes, and snippets.

@nyinyithann
Created December 24, 2018 16:28
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 nyinyithann/ae20e97c9e7fa871c6d71d6cf97b6bf0 to your computer and use it in GitHub Desktop.
Save nyinyithann/ae20e97c9e7fa871c6d71d6cf97b6bf0 to your computer and use it in GitHub Desktop.
using closure as callback
use std::collections::HashMap;
fn main() {
let mut router = BasicRouter::new();
router.add_route("/", |req| Response {
code: 200,
headers: req.headers.clone(),
body: vec![1, 2, 3, 4, 5],
});
router.add_route("/rust/doc", |_| Response {
code: 200,
headers: HashMap::new(),
body: vec![80, 127, 23],
});
let res1 = router.handle_route(&Request {
method: "Get".to_owned(),
url: "/".to_owned(),
headers: HashMap::new(),
body: vec![],
});
let res2 = router.handle_route(&Request {
method: "Get".to_owned(),
url: "/rust/doc".to_owned(),
headers: HashMap::new(),
body: vec![],
});
println!(" res1 : {:?} \n res2: {:?}", res1, res2);
}
#[derive(Debug)]
struct Request {
method: String,
url: String,
headers: HashMap<String, String>,
body: Vec<u8>,
}
#[derive(Debug)]
struct Response {
code: u32,
headers: HashMap<String, String>,
body: Vec<u8>,
}
type RequestHandler = Box<Fn(&Request) -> Response>;
struct BasicRouter {
routes: HashMap<String, RequestHandler>,
}
impl BasicRouter {
pub fn new() -> BasicRouter {
BasicRouter {
routes: HashMap::new(),
}
}
pub fn add_route<H>(&mut self, url: &str, handler: H)
where
H: 'static + Fn(&Request) -> Response,
{
self.routes.insert(url.to_owned(), Box::new(handler));
}
pub fn handle_route(&self, req: &Request) -> Response {
match self.routes.get(&req.url) {
None => Response {
code: 404,
headers: HashMap::new(),
body: Vec::new(),
},
Some(handler) => handler(req),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment