From 42f9e1034bea2564f8f2d4442aaa372f72ade5f9 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Thu, 7 Jun 2018 20:00:54 -0700 Subject: [PATCH] add Host predicate --- src/application.rs | 2 +- src/pred.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/application.rs b/src/application.rs index 254238b53..29054dad2 100644 --- a/src/application.rs +++ b/src/application.rs @@ -306,7 +306,7 @@ where /// # use actix_web::*; /// # fn main() { /// App::new() - /// .filter(pred::Get()) + /// .filter(pred::Hoat("www.rust-lang.org")) /// .resource("/path", |r| r.f(|_| HttpResponse::Ok())) /// # .finish(); /// # } diff --git a/src/pred.rs b/src/pred.rs index 90a0d61f6..bdc286c01 100644 --- a/src/pred.rs +++ b/src/pred.rs @@ -192,6 +192,45 @@ impl Predicate for HeaderPredicate { } } +/// Return predicate that matches if request contains specified Host name. +/// +/// ```rust +/// # extern crate actix_web; +/// use actix_web::{pred, App, HttpResponse}; +/// +/// fn main() { +/// App::new().resource("/index.html", |r| { +/// r.route() +/// .filter(pred::Host("www.rust-lang.org")) +/// .f(|_| HttpResponse::MethodNotAllowed()) +/// }); +/// } +/// ``` +pub fn Host>(host: H) -> HostPredicate { + HostPredicate(host.as_ref().to_string(), None, PhantomData) +} + +#[doc(hidden)] +pub struct HostPredicate(String, Option, PhantomData); + +impl HostPredicate { + /// Set reuest scheme to match + pub fn scheme>(&mut self, scheme: H) { + self.1 = Some(scheme.as_ref().to_string()) + } +} + +impl Predicate for HostPredicate { + fn check(&self, req: &mut HttpRequest) -> bool { + let info = req.connection_info(); + if let Some(ref scheme) = self.1 { + self.0 == info.host() && scheme == info.scheme() + } else { + self.0 == info.host() + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -224,6 +263,28 @@ mod tests { assert!(!pred.check(&mut req)); } + #[test] + fn test_host() { + let mut headers = HeaderMap::new(); + headers.insert( + header::HOST, + header::HeaderValue::from_static("www.rust-lang.org"), + ); + let mut req = HttpRequest::new( + Method::GET, + Uri::from_str("/").unwrap(), + Version::HTTP_11, + headers, + None, + ); + + let pred = Host("www.rust-lang.org"); + assert!(pred.check(&mut req)); + + let pred = Host("localhost"); + assert!(!pred.check(&mut req)); + } + #[test] fn test_methods() { let mut req = HttpRequest::new(