From af18bf2ebe0b90df11d33a013d8faaec0e95c45a Mon Sep 17 00:00:00 2001 From: Compositr Date: Fri, 1 Nov 2024 21:33:19 +1100 Subject: [PATCH] refactor: update handler function types to use boxed dynamic dispatch --- src/handlers.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/handlers.rs b/src/handlers.rs index b2dbbe1..ca1c94b 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -7,11 +7,12 @@ use std::{ net::{Shutdown, TcpListener}, }; -type HandlerFn = fn(Request) -> Response<'static>; +type DynHandlerFn = dyn Fn(Request) -> Response<'static>; +type BoxedHandlerFn = Box; // Collection of handlers for requests pub struct Handlers { - matchers: HashMap, + matchers: HashMap, } impl Handlers { @@ -30,8 +31,8 @@ impl Handlers { /// /// path: Path to match (no trailing /) /// handler: Function to handle the request. Must return a Response - pub fn add_handler(&mut self, path: &str, handler: HandlerFn) { - self.matchers.insert(path.to_string(), handler); + pub fn add_handler(&mut self, path: &str, handler: impl Fn(Request) -> Response<'static> + 'static) { + self.matchers.insert(path.to_string(), Box::from(handler)); } /// Bind these handlers to a listener in order to handle incoming requests @@ -65,11 +66,11 @@ impl Handlers { } } - fn match_handler(&self, url: &URL) -> Option { + fn match_handler(&self, url: &URL) -> Option<&BoxedHandlerFn> { 'matching_loop: for (path, handler) in self.matchers.iter() { // Exact match if path == &url.path { - return Some(*handler); + return Some(handler); }; // Segment matching @@ -109,7 +110,7 @@ impl Handlers { break 'matching_loop; } - return Some(*handler); + return Some(handler); } None