1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-25 09:59:21 +02:00

introduce route predicates

This commit is contained in:
Nikolay Kim
2017-12-04 13:32:05 -08:00
parent 57fd35ffc1
commit 3bf3738e65
20 changed files with 370 additions and 122 deletions

View File

@ -118,7 +118,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// A variable part is specified in the form `{identifier}`, where
/// the identifier can be used later in a request handler to access the matched
/// value for that part. This is done by looking up the identifier
/// in the `Params` object returned by `Request.match_info()` method.
/// in the `Params` object returned by `HttpRequest.match_info()` method.
///
/// By default, each part matches the regular expression `[^{}/]+`.
///
@ -134,8 +134,8 @@ impl<S> ApplicationBuilder<S> where S: 'static {
/// fn main() {
/// let app = Application::default("/")
/// .resource("/test", |r| {
/// r.get(|req| httpcodes::HTTPOk);
/// r.handler(Method::HEAD, |req| httpcodes::HTTPMethodNotAllowed);
/// r.method(Method::GET).handler(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).handler(|_| httpcodes::HTTPMethodNotAllowed);
/// })
/// .finish();
/// }

View File

@ -75,6 +75,7 @@ pub mod error;
pub mod httpcodes;
pub mod multipart;
pub mod middlewares;
pub mod pred;
pub use error::{Error, Result};
pub use encoding::ContentEncoding;
pub use body::{Body, Binary};
@ -83,7 +84,7 @@ pub use httprequest::{HttpRequest, UrlEncoded};
pub use httpresponse::HttpResponse;
pub use payload::{Payload, PayloadItem};
pub use route::{Reply, Json, FromRequest};
pub use resource::Resource;
pub use resource::{Route, Resource};
pub use recognizer::Params;
pub use server::HttpServer;
pub use context::HttpContext;

View File

@ -21,8 +21,8 @@ use middlewares::{Response, Middleware};
/// .header("X-Version", "0.2")
/// .finish())
/// .resource("/test", |r| {
/// r.get(|req| httpcodes::HTTPOk);
/// r.handler(Method::HEAD, |req| httpcodes::HTTPMethodNotAllowed);
/// r.method(Method::GET).handler(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).handler(|_| httpcodes::HTTPMethodNotAllowed);
/// })
/// .finish();
/// }

148
src/pred.rs Normal file
View File

@ -0,0 +1,148 @@
//! Route match predicates
#![allow(non_snake_case)]
use std::marker::PhantomData;
use http;
use http::{header, HttpTryFrom};
use httprequest::HttpRequest;
/// Trait defines resource route predicate.
/// Predicate can modify request object. It is also possible to
/// to store extra attributes on request by using `.extensions()` method.
pub trait Predicate<S> {
/// Check if request matches predicate
fn check(&self, &mut HttpRequest<S>) -> bool;
}
/// Return predicate that matches if any of supplied predicate matches.
pub fn Any<T, S: 'static>(preds: T) -> Box<Predicate<S>>
where T: IntoIterator<Item=Box<Predicate<S>>>
{
Box::new(AnyPredicate(preds.into_iter().collect()))
}
struct AnyPredicate<S>(Vec<Box<Predicate<S>>>);
impl<S: 'static> Predicate<S> for AnyPredicate<S> {
fn check(&self, req: &mut HttpRequest<S>) -> bool {
for p in &self.0 {
if p.check(req) {
return true
}
}
false
}
}
/// Return predicate that matches if all of supplied predicate matches.
pub fn All<T, S: 'static>(preds: T) -> Box<Predicate<S>>
where T: IntoIterator<Item=Box<Predicate<S>>>
{
Box::new(AllPredicate(preds.into_iter().collect()))
}
struct AllPredicate<S>(Vec<Box<Predicate<S>>>);
impl<S: 'static> Predicate<S> for AllPredicate<S> {
fn check(&self, req: &mut HttpRequest<S>) -> bool {
for p in &self.0 {
if !p.check(req) {
return false
}
}
true
}
}
/// Return predicate that matches if supplied predicate does not match.
pub fn Not<S: 'static>(pred: Box<Predicate<S>>) -> Box<Predicate<S>>
{
Box::new(NotPredicate(pred))
}
struct NotPredicate<S>(Box<Predicate<S>>);
impl<S: 'static> Predicate<S> for NotPredicate<S> {
fn check(&self, req: &mut HttpRequest<S>) -> bool {
!self.0.check(req)
}
}
/// Http method predicate
struct MethodPredicate<S>(http::Method, PhantomData<S>);
impl<S: 'static> Predicate<S> for MethodPredicate<S> {
fn check(&self, req: &mut HttpRequest<S>) -> bool {
*req.method() == self.0
}
}
/// Predicate to match *GET* http method
pub fn Get<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::GET, PhantomData))
}
/// Predicate to match *POST* http method
pub fn Post<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::POST, PhantomData))
}
/// Predicate to match *PUT* http method
pub fn Put<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::PUT, PhantomData))
}
/// Predicate to match *DELETE* http method
pub fn Delete<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::DELETE, PhantomData))
}
/// Predicate to match *HEAD* http method
pub fn Head<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::HEAD, PhantomData))
}
/// Predicate to match *OPTIONS* http method
pub fn Options<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::OPTIONS, PhantomData))
}
/// Predicate to match *CONNECT* http method
pub fn Connect<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::CONNECT, PhantomData))
}
/// Predicate to match *PATCH* http method
pub fn Patch<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::PATCH, PhantomData))
}
/// Predicate to match *TRACE* http method
pub fn Trace<S: 'static>() -> Box<Predicate<S>> {
Box::new(MethodPredicate(http::Method::TRACE, PhantomData))
}
/// Predicate to match specified http method
pub fn Method<S: 'static>(method: http::Method) -> Box<Predicate<S>> {
Box::new(MethodPredicate(method, PhantomData))
}
/// Return predicate that matches if request contains specified header and value.
pub fn Header<S: 'static>(name: &'static str, value: &'static str) -> Box<Predicate<S>>
{
Box::new(HeaderPredicate(header::HeaderName::try_from(name).unwrap(),
header::HeaderValue::from_static(value),
PhantomData))
}
struct HeaderPredicate<S>(header::HeaderName, header::HeaderValue, PhantomData<S>);
impl<S: 'static> Predicate<S> for HeaderPredicate<S> {
fn check(&self, req: &mut HttpRequest<S>) -> bool {
if let Some(val) = req.headers().get(&self.0) {
return val == self.1
}
false
}
}

View File

@ -76,11 +76,14 @@ impl Params {
///
/// If keyed parameter is not available empty string is used as default value.
///
/// ```rust,ignore
/// fn index(req: HttpRequest) -> String {
/// ```rust
/// # extern crate actix_web;
/// # use actix_web::*;
/// fn index(req: HttpRequest) -> Result<String> {
/// let ivalue: isize = req.match_info().query("val")?;
/// format!("isuze value: {:?}", ivalue)
/// Ok(format!("isuze value: {:?}", ivalue))
/// }
/// # fn main() {}
/// ```
pub fn query<T: FromParam>(&self, key: &str) -> Result<T, <T as FromParam>::Err>
{

View File

@ -1,34 +1,111 @@
use std::marker::PhantomData;
use std::collections::HashMap;
use http::Method;
use futures::Future;
use error::Error;
use pred::{self, Predicate};
use route::{Reply, Handler, FromRequest, RouteHandler, AsyncHandler, WrapHandler};
use httpcodes::HTTPNotFound;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::{HTTPNotFound, HTTPMethodNotAllowed};
/// Resource route definition. Route uses builder-like pattern for configuration.
pub struct Route<S> {
preds: Vec<Box<Predicate<S>>>,
handler: Box<RouteHandler<S>>,
}
impl<S: 'static> Default for Route<S> {
fn default() -> Route<S> {
Route {
preds: Vec::new(),
handler: Box::new(WrapHandler::new(|_| HTTPNotFound)),
}
}
}
impl<S: 'static> Route<S> {
fn check(&self, req: &mut HttpRequest<S>) -> bool {
for pred in &self.preds {
if !pred.check(req) {
return false
}
}
true
}
fn handle(&self, req: HttpRequest<S>) -> Reply {
self.handler.handle(req)
}
/// Add match predicate to route.
pub fn p(&mut self, p: Box<Predicate<S>>) -> &mut Self {
self.preds.push(p);
self
}
/// Add predicates to route.
pub fn predicates<P>(&mut self, preds: P) -> &mut Self
where P: IntoIterator<Item=Box<Predicate<S>>>
{
self.preds.extend(preds.into_iter());
self
}
/// Add method check to route. This method could be called multiple times.
pub fn method(&mut self, method: Method) -> &mut Self {
self.preds.push(pred::Method(method));
self
}
/// Set handler function. Usually call to this method is last call
/// during route configuration, because it does not return reference to self.
pub fn handler<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static,
{
self.handler = Box::new(WrapHandler::new(handler));
}
/// Set handler function.
pub fn async<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: Future<Item=HttpResponse, Error=Error> + 'static,
{
self.handler = Box::new(AsyncHandler::new(handler));
}
}
/// Http resource
///
/// `Resource` is an entry in route table which corresponds to requested URL.
///
/// Resource in turn has at least one route.
/// Route corresponds to handling HTTP method by calling route handler.
/// Route consists of an object that implements `Handler` trait (handler)
/// and list of predicates (objects that implement `Predicate` trait).
/// Route uses builder-like pattern for configuration.
/// During request handling, resource object iterate through all routes
/// and check all predicates for specific route, if request matches all predicates route
/// route considired matched and route handler get called.
///
/// ```rust
/// extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let app = actix_web::Application::default("/")
/// .resource("/", |r| r.get(|_| actix_web::HttpResponse::Ok()))
/// let app = Application::default("/")
/// .resource(
/// "/", |r| r.route().method(Method::GET).handler(|r| HttpResponse::Ok()))
/// .finish();
/// }
pub struct Resource<S=()> {
name: String,
state: PhantomData<S>,
routes: HashMap<Method, Box<RouteHandler<S>>>,
routes: Vec<Route<S>>,
default: Box<RouteHandler<S>>,
}
@ -37,8 +114,8 @@ impl<S> Default for Resource<S> {
Resource {
name: String::new(),
state: PhantomData,
routes: HashMap::new(),
default: Box::new(HTTPMethodNotAllowed)}
routes: Vec::new(),
default: Box::new(HTTPNotFound)}
}
}
@ -48,7 +125,7 @@ impl<S> Resource<S> where S: 'static {
Resource {
name: String::new(),
state: PhantomData,
routes: HashMap::new(),
routes: Vec::new(),
default: Box::new(HTTPNotFound)}
}
@ -57,65 +134,48 @@ impl<S> Resource<S> where S: 'static {
self.name = name.into();
}
/// Register handler for specified method.
pub fn handler<F, R>(&mut self, method: Method, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static,
{
self.routes.insert(method, Box::new(WrapHandler::new(handler)));
/// Register a new route and return mutable reference to *Route* object.
/// *Route* is used for route configuration, i.e. adding predicates, setting up handler.
///
/// ```rust
/// extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::default("/")
/// .resource(
/// "/", |r| r.route()
/// .p(pred::Any(vec![pred::Get(), pred::Put()]))
/// .p(pred::Header("Content-Type", "text/plain"))
/// .handler(|r| HttpResponse::Ok()))
/// .finish();
/// }
pub fn route(&mut self) -> &mut Route<S> {
self.routes.push(Route::default());
self.routes.last_mut().unwrap()
}
/// Register async handler for specified method.
pub fn async<F, R>(&mut self, method: Method, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: Future<Item=HttpResponse, Error=Error> + 'static,
{
self.routes.insert(method, Box::new(AsyncHandler::new(handler)));
/// Register a new route and add method check to route.
pub fn method(&mut self, method: Method) -> &mut Route<S> {
self.routes.push(Route::default());
self.routes.last_mut().unwrap().method(method)
}
/// Default handler is used if no matched route found.
/// By default `HTTPMethodNotAllowed` is used.
pub fn default_handler<H>(&mut self, handler: H) where H: Handler<S>
{
/// By default `HTTPNotFound` is used.
pub fn default_handler<H>(&mut self, handler: H) where H: Handler<S> {
self.default = Box::new(WrapHandler::new(handler));
}
/// Register handler for `GET` method.
pub fn get<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static, {
self.routes.insert(Method::GET, Box::new(WrapHandler::new(handler)));
}
/// Register handler for `POST` method.
pub fn post<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static, {
self.routes.insert(Method::POST, Box::new(WrapHandler::new(handler)));
}
/// Register handler for `PUT` method.
pub fn put<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static, {
self.routes.insert(Method::PUT, Box::new(WrapHandler::new(handler)));
}
/// Register handler for `DELETE` method.
pub fn delete<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static, {
self.routes.insert(Method::DELETE, Box::new(WrapHandler::new(handler)));
}
}
impl<S: 'static> RouteHandler<S> for Resource<S> {
fn handle(&self, req: HttpRequest<S>) -> Reply {
if let Some(handler) = self.routes.get(req.method()) {
handler.handle(req)
} else {
self.default.handle(req)
fn handle(&self, mut req: HttpRequest<S>) -> Reply {
for route in &self.routes {
if route.check(&mut req) {
return route.handle(req)
}
}
self.default.handle(req)
}
}

View File

@ -43,7 +43,7 @@
//!
//! fn main() {
//! Application::default("/")
//! .resource("/ws/", |r| r.get(ws_index)) // <- register websocket route
//! .resource("/ws/", |r| r.method(Method::GET).handler(ws_index)) // <- register websocket route
//! .finish();
//! }
//! ```