From 132917c61682deeb3e0bbc7d61758d87cd83cf6a Mon Sep 17 00:00:00 2001 From: Jan Klattenhoff Date: Wed, 21 Aug 2024 08:12:12 +0200 Subject: [PATCH] Add controllers --- src/controller.rs | 7 +++++++ src/lib.rs | 1 + src/router.rs | 10 +++++++++- 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 src/controller.rs diff --git a/src/controller.rs b/src/controller.rs new file mode 100644 index 0000000..9caebea --- /dev/null +++ b/src/controller.rs @@ -0,0 +1,7 @@ +use std::collections::HashMap; + +use tiny_http::Request; + +pub trait Controller { + fn register_routes(&self) -> HashMap; +} diff --git a/src/lib.rs b/src/lib.rs index 530c2ac..d4c151f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ pub mod router; +pub mod controller; pub mod entities; pub mod utilities; pub mod template; diff --git a/src/router.rs b/src/router.rs index 9999ab5..6449880 100644 --- a/src/router.rs +++ b/src/router.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use tiny_http::Request; -use crate::{entities::request::Url, utilities::responses::respond_not_found}; +use crate::{controller::Controller, entities::request::Url, utilities::responses::respond_not_found}; pub struct Router { @@ -23,6 +23,14 @@ impl Router { } } + 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); }