joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
Documentation
use crate::method::Method;
use crate::request::Request;
use crate::response::Response;

/// Runs around every request.
///
/// Joist uses `before`/`after` hooks rather than an onion of `next()` calls.
/// The onion is more general: it lets one middleware wrap the handler and hold
/// state across it, which is how request timing is usually done. Hooks cannot
/// do that. In exchange the ordering is obvious, there is no boxed closure
/// chain rebuilt per request, and writing one does not require thinking about
/// lifetimes. If you need to wrap, wrap the handler itself.
///
/// `before` hooks run in registration order. Returning a response from one
/// skips the remaining `before` hooks and the handler. `after` hooks run in
/// reverse order and always run, even after a short circuit, so a logger still
/// sees the request an authentication middleware rejected.
pub trait Middleware: Send + Sync + 'static {
    fn before(&self, _req: &mut Request) -> Option<Response> {
        None
    }

    fn after(&self, _req: &Request, res: Response) -> Response {
        res
    }
}

/// Writes one line per request to stderr.
///
/// Deliberately not a timer: an `after` hook cannot see when `before` ran, so
/// reporting a duration here would mean inventing one.
pub struct RequestLog;

impl Middleware for RequestLog {
    fn after(&self, req: &Request, res: Response) -> Response {
        eprintln!(
            "{} {} {} {}",
            req.peer
                .map(|p| p.ip().to_string())
                .unwrap_or_else(|| "-".into()),
            req.method,
            req.target,
            res.status.code()
        );
        res
    }
}

/// Adds CORS headers, and answers preflight requests.
pub struct Cors {
    origin: String,
    methods: String,
    headers: String,
    max_age: Option<u32>,
}

impl Cors {
    /// Allow a single origin. Pass `*` to allow any, which browsers refuse to
    /// combine with credentials.
    pub fn new(origin: &str) -> Cors {
        Cors {
            origin: origin.to_string(),
            methods: "GET, POST, PUT, PATCH, DELETE, OPTIONS".to_string(),
            headers: "Content-Type, Authorization".to_string(),
            max_age: None,
        }
    }

    pub fn methods(mut self, methods: &str) -> Cors {
        self.methods = methods.to_string();
        self
    }

    pub fn headers(mut self, headers: &str) -> Cors {
        self.headers = headers.to_string();
        self
    }

    pub fn max_age(mut self, seconds: u32) -> Cors {
        self.max_age = Some(seconds);
        self
    }
}

impl Middleware for Cors {
    fn before(&self, req: &mut Request) -> Option<Response> {
        // Answer the preflight without troubling the router. The headers are
        // added by `after`, which runs for short-circuited responses too.
        if req.method == Method::Options {
            Some(Response::no_content())
        } else {
            None
        }
    }

    fn after(&self, _req: &Request, mut res: Response) -> Response {
        res.headers.set("Access-Control-Allow-Origin", &self.origin);
        res.headers
            .set("Access-Control-Allow-Methods", &self.methods);
        res.headers
            .set("Access-Control-Allow-Headers", &self.headers);
        if let Some(age) = self.max_age {
            res.headers.set("Access-Control-Max-Age", &age.to_string());
        }
        res
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::status::Status;

    fn request(method: Method) -> Request {
        Request::new(method, "/")
    }

    #[test]
    fn cors_answers_preflight() {
        let cors = Cors::new("https://example.com");
        let mut req = request(Method::Options);
        let res = cors.before(&mut req).expect("preflight short-circuits");
        assert_eq!(res.status, Status::NO_CONTENT);
    }

    #[test]
    fn cors_does_not_short_circuit_real_requests() {
        let cors = Cors::new("*");
        let mut req = request(Method::Get);
        assert!(cors.before(&mut req).is_none());
    }

    #[test]
    fn cors_sets_headers_on_the_way_out() {
        let cors = Cors::new("https://example.com").max_age(600);
        let req = request(Method::Get);
        let res = cors.after(&req, Response::ok());
        assert_eq!(
            res.headers.get("Access-Control-Allow-Origin"),
            Some("https://example.com")
        );
        assert_eq!(res.headers.get("Access-Control-Max-Age"), Some("600"));
    }

    #[test]
    fn default_middleware_is_a_passthrough() {
        struct Noop;
        impl Middleware for Noop {}

        let mut req = request(Method::Get);
        assert!(Noop.before(&mut req).is_none());
        let res = Noop.after(&req, Response::text("unchanged"));
        assert_eq!(res.body().as_bytes(), Some(&b"unchanged"[..]));
    }
}