From 7ae322a1bb4ed93f20e98dcb3416057808dbd434 Mon Sep 17 00:00:00 2001 From: Fuwn Date: Sun, 27 Mar 2022 00:05:52 +0000 Subject: feat(router): modules --- examples/windmark.rs | 5 ++++- src/lib.rs | 35 ++++++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/examples/windmark.rs b/examples/windmark.rs index 5568249..e1cb513 100644 --- a/examples/windmark.rs +++ b/examples/windmark.rs @@ -21,7 +21,7 @@ #[macro_use] extern crate log; -use windmark::response::Response; +use windmark::Response; fn main() -> std::io::Result<()> { windmark::Router::new() @@ -29,6 +29,9 @@ fn main() -> std::io::Result<()> { .set_certificate_chain_file("windmark_pair.pem") .enable_default_logger(true) .set_error_handler(|_| Response::PermanentFailure("error...".to_string())) + .attach(|r| { + r.mount("/module", |_| Response::Success("This is a module!".into())); + }) .set_pre_route_callback(|stream, url, _| { info!( "accepted connection from {} to {}", diff --git a/src/lib.rs b/src/lib.rs index 4f68ca6..a0f02f5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,10 +41,11 @@ use std::{net::TcpStream, sync::Arc}; use matchit::Params; use openssl::ssl::{self, SslAcceptor, SslMethod}; +pub use response::Response; use url::Url; use crate::{ - response::{to_value_set_status, Response}, + response::to_value_set_status, returnable::{ErrorContext, RouteContext}, }; @@ -119,7 +120,7 @@ impl Router { /// # Examples /// /// ```rust - /// use windmark::response::Response; + /// use windmark::Response; /// /// windmark::Router::new() /// .mount("/", |_| Response::Success("This is the index page!".into())) @@ -147,9 +148,7 @@ impl Router { /// /// ```rust /// windmark::Router::new().set_error_handler(|_| { - /// windmark::response::Response::Success( - /// "You have encountered an error!".into(), - /// ) + /// windmark::Response::Success("You have encountered an error!".into()) /// }); /// ``` pub fn set_error_handler( @@ -439,6 +438,32 @@ impl Router { self } + + /// Attach a module to a `Router`. + /// + /// A module is an extension or middleware to a `Router`. Modules get full + /// access to the `Router`, but can be extended by a third party. + /// + /// # Examples + /// + /// ```rust + /// use windmark::Response; + /// + /// windmark::Router::new().attach(|r| { + /// r.mount("/module", |_| Response::Success("This is a module!".into())); + /// r.set_error_handler(|_| { + /// Response::NotFound( + /// "This error handler has been implemented by a module!".into(), + /// ) + /// }); + /// }); + /// ``` + pub fn attach(&mut self, mut module: F) -> &mut Self + where F: FnMut(&mut Self) { + module(self); + + self + } } impl Default for Router { fn default() -> Self { -- cgit v1.2.3