joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
Documentation
use crate::config::Config;
use crate::router::Router;

/// A reusable bundle of routes.
///
/// A plugin is handed the router at startup and registers whatever it needs.
/// There is deliberately no hook for mutating another plugin's routes or
/// wrapping the dispatcher: a plugin that can rewrite the application from
/// underneath it is a debugging problem, not a feature.
pub trait Plugin {
    /// Used in startup logging and error messages.
    fn name(&self) -> &'static str;

    /// Register routes. Called once, before the listener is bound.
    fn install(self: Box<Self>, router: &mut Router, config: &Config);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::method::Method;
    use crate::request::Request;
    use crate::response::Response;

    struct Health {
        path: &'static str,
    }

    impl Plugin for Health {
        fn name(&self) -> &'static str {
            "health"
        }

        fn install(self: Box<Self>, router: &mut Router, config: &Config) {
            let label = config.get_or("service.name", "unknown").to_string();
            router.get(self.path, move |_| Response::text(format!("ok {label}")));
        }
    }

    #[test]
    fn a_plugin_registers_its_routes() {
        let mut router = Router::new();
        let mut config = Config::new();
        config.set("service.name", "billing");

        Box::new(Health { path: "/healthz" }).install(&mut router, &config);
        assert_eq!(router.len(), 1);

        let mut req = Request::new(Method::Get, "/healthz");
        assert_eq!(
            router.dispatch(&mut req).body().as_bytes(),
            Some(&b"ok billing"[..])
        );
    }
}