use crate::method::Method;
use crate::request::Request;
use crate::response::Response;
pub trait Middleware: Send + Sync + 'static {
fn before(&self, _req: &mut Request) -> Option<Response> {
None
}
fn after(&self, _req: &Request, res: Response) -> Response {
res
}
}
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
}
}
pub struct Cors {
origin: String,
methods: String,
headers: String,
max_age: Option<u32>,
}
impl Cors {
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> {
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"[..]));
}
}