use crate::method::Method;
use crate::request::Request;
use crate::response::Response;
use crate::status::Status;
pub type Handler = Box<dyn Fn(&Request) -> Response + Send + Sync + 'static>;
#[derive(Debug, Clone, PartialEq)]
enum Segment {
Static(String),
Param(String),
Wildcard(String),
}
struct Route {
method: Method,
segments: Vec<Segment>,
handler: Handler,
}
pub struct Router {
routes: Vec<Route>,
fallback: Option<Handler>,
}
impl Default for Router {
fn default() -> Self {
Router::new()
}
}
impl Router {
pub fn new() -> Router {
Router {
routes: Vec::new(),
fallback: None,
}
}
pub fn route<F>(&mut self, method: Method, path: &str, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.routes.push(Route {
method,
segments: parse_pattern(path),
handler: Box::new(handler),
});
self
}
pub fn get<F>(&mut self, path: &str, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.route(Method::Get, path, handler)
}
pub fn post<F>(&mut self, path: &str, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.route(Method::Post, path, handler)
}
pub fn put<F>(&mut self, path: &str, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.route(Method::Put, path, handler)
}
pub fn patch<F>(&mut self, path: &str, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.route(Method::Patch, path, handler)
}
pub fn delete<F>(&mut self, path: &str, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.route(Method::Delete, path, handler)
}
pub fn options<F>(&mut self, path: &str, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.route(Method::Options, path, handler)
}
pub fn fallback<F>(&mut self, handler: F) -> &mut Router
where
F: Fn(&Request) -> Response + Send + Sync + 'static,
{
self.fallback = Some(Box::new(handler));
self
}
pub fn len(&self) -> usize {
self.routes.len()
}
pub fn is_empty(&self) -> bool {
self.routes.is_empty()
}
pub fn dispatch(&self, req: &mut Request) -> Response {
let path: Vec<&str> = req.path.split('/').filter(|s| !s.is_empty()).collect();
let mut path_matched = false;
let mut allowed: Vec<&'static str> = Vec::new();
for route in &self.routes {
let params = match match_segments(&route.segments, &path) {
Some(p) => p,
None => continue,
};
let method_ok = route.method == req.method
|| (req.method == Method::Head && route.method == Method::Get);
if method_ok {
req.set_params(params);
return (route.handler)(req);
}
path_matched = true;
if !allowed.contains(&route.method.as_str()) {
allowed.push(route.method.as_str());
}
}
if path_matched {
return Response::error(Status::METHOD_NOT_ALLOWED, "method not allowed")
.header("Allow", &allowed.join(", "));
}
match &self.fallback {
Some(handler) => handler(req),
None => Response::not_found(),
}
}
}
fn parse_pattern(path: &str) -> Vec<Segment> {
path.split('/')
.filter(|s| !s.is_empty())
.map(|s| {
if let Some(name) = s.strip_prefix(':') {
Segment::Param(name.to_string())
} else if let Some(name) = s.strip_prefix('*') {
Segment::Wildcard(name.to_string())
} else {
Segment::Static(s.to_string())
}
})
.collect()
}
fn match_segments(pattern: &[Segment], path: &[&str]) -> Option<Vec<(String, String)>> {
let mut params = Vec::new();
let mut i = 0;
for segment in pattern {
match segment {
Segment::Static(expected) => {
if i >= path.len() || path[i] != expected {
return None;
}
i += 1;
}
Segment::Param(name) => {
if i >= path.len() {
return None;
}
params.push((name.clone(), path[i].to_string()));
i += 1;
}
Segment::Wildcard(name) => {
let rest = if i < path.len() {
path[i..].join("/")
} else {
String::new()
};
params.push((name.clone(), rest));
return Some(params);
}
}
}
if i == path.len() {
Some(params)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
fn request(method: Method, path: &str) -> Request {
Request::new(method, path)
}
fn body_of(res: &Response) -> Vec<u8> {
res.body().as_bytes().unwrap().to_vec()
}
#[test]
fn matches_static_routes() {
let mut r = Router::new();
r.get("/health", |_| Response::text("ok"));
let mut req = request(Method::Get, "/health");
let res = r.dispatch(&mut req);
assert_eq!(res.status, Status::OK);
assert_eq!(body_of(&res), b"ok");
}
#[test]
fn captures_path_parameters() {
let mut r = Router::new();
r.get("/users/:id/posts/:post", |req| {
Response::text(format!(
"{}:{}",
req.param("id").unwrap(),
req.param("post").unwrap()
))
});
let mut req = request(Method::Get, "/users/42/posts/abc");
assert_eq!(body_of(&r.dispatch(&mut req)), b"42:abc");
}
#[test]
fn wildcard_captures_the_rest() {
let mut r = Router::new();
r.get("/static/*path", |req| {
Response::text(req.param("path").unwrap().to_string())
});
let mut req = request(Method::Get, "/static/css/site/main.css");
assert_eq!(body_of(&r.dispatch(&mut req)), b"css/site/main.css");
let mut bare = request(Method::Get, "/static");
assert_eq!(body_of(&r.dispatch(&mut bare)), b"");
}
#[test]
fn unmatched_path_is_404() {
let r = Router::new();
let mut req = request(Method::Get, "/nope");
assert_eq!(r.dispatch(&mut req).status, Status::NOT_FOUND);
}
#[test]
fn wrong_method_is_405_with_allow() {
let mut r = Router::new();
r.get("/thing", |_| Response::ok());
r.delete("/thing", |_| Response::ok());
let mut req = request(Method::Post, "/thing");
let res = r.dispatch(&mut req);
assert_eq!(res.status, Status::METHOD_NOT_ALLOWED);
assert_eq!(res.headers.get("Allow"), Some("GET, DELETE"));
}
#[test]
fn head_is_served_by_the_get_route() {
let mut r = Router::new();
r.get("/page", |_| Response::text("body"));
let mut req = request(Method::Head, "/page");
assert_eq!(r.dispatch(&mut req).status, Status::OK);
}
#[test]
fn first_registered_route_wins() {
let mut r = Router::new();
r.get("/files/special", |_| Response::text("specific"));
r.get("/files/:name", |_| Response::text("generic"));
let mut req = request(Method::Get, "/files/special");
assert_eq!(body_of(&r.dispatch(&mut req)), b"specific");
}
#[test]
fn fallback_replaces_the_default_404() {
let mut r = Router::new();
r.fallback(|_| Response::text("custom").with_status(Status::NOT_FOUND));
let mut req = request(Method::Get, "/anything");
let res = r.dispatch(&mut req);
assert_eq!(res.status, Status::NOT_FOUND);
assert_eq!(body_of(&res), b"custom");
}
#[test]
fn trailing_slashes_do_not_change_matching() {
let mut r = Router::new();
r.get("/a/b", |_| Response::text("hit"));
for path in ["/a/b", "/a/b/", "//a//b//"] {
let mut req = request(Method::Get, path);
assert_eq!(body_of(&r.dispatch(&mut req)), b"hit", "for {path}");
}
}
#[test]
fn longer_path_does_not_match_shorter_pattern() {
let mut r = Router::new();
r.get("/a", |_| Response::ok());
let mut req = request(Method::Get, "/a/b");
assert_eq!(r.dispatch(&mut req).status, Status::NOT_FOUND);
}
}