Change logic of the router

This commit is contained in:
Jan Gleytenhoover 2024-08-21 12:42:52 +02:00
parent 132917c616
commit 036c6f873e
Signed by: jank
GPG Key ID: B267751B8AE29EFE

@ -1,63 +1,10 @@
use std::collections::HashMap;
use tiny_http::Request;
use crate::{controller::Controller, entities::request::Url, utilities::responses::respond_not_found};
use crate::controller::Controller;
pub struct Router {
routes: HashMap<String, fn(Request)>,
pub trait Router {
fn new() -> Self;
fn route(&self, request: Request);
fn add_controller(&mut self, controller: impl Controller);
fn add_route(&mut self, route: &str, route_function: fn(Request));
}
impl Router {
pub fn new() -> Self {
let routes = HashMap::new();
Router { routes }
}
pub async fn route(&self, request: Request) {
match self.routes.get(&request.get_url_without_parameters()) {
Some(handler) => handler(request),
None => respond_not_found(request),
}
}
pub fn add_controller(&mut self, controller: impl Controller) {
let new_routes = controller.register_routes();
let mut final_routes = self.routes.clone();
final_routes.extend(new_routes);
self.routes = final_routes;
}
pub fn add_route(&mut self, route: &str, route_function: fn(Request)) {
self.routes.insert(route.to_string(), route_function);
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use tiny_http::Request;
use super::Router;
#[test]
fn test_add_route() {
let mut router = Router::new();
fn test_route(_request: Request) {
}
router.add_route("/test", test_route as fn(Request));
let mut expected = HashMap::new();
expected.insert("/test".to_string(), test_route as fn(Request));
assert_eq!(router.routes, expected);
}
}