diff --git a/README.md b/README.md index d128ff999..695e67675 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,8 @@ fn main() { HttpServer::new( Application::default("/") .middleware(middlewares::Logger::default()) // <- register logger middleware - .resource("/ws/", |r| r.get(|req| ws::start(req, MyWebSocket))) // <- websocket route + .resource("/ws/", |r| r.method(Method::GET) + .handler(|req| ws::start(req, MyWebSocket))) // <- websocket route .route("/", fs::StaticFiles::new("examples/static/", true))) // <- serve static files .serve::<_, ()>("127.0.0.1:8080").unwrap(); diff --git a/examples/basic.rs b/examples/basic.rs index f42642f0e..a7e375110 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -69,11 +69,11 @@ fn main() { // register simple handle r, handle all methods .handler("/index.html", index) // with path parameters - .resource("/user/{name}/", |r| r.handler(Method::GET, with_param)) + .resource("/user/{name}/", |r| r.route().method(Method::GET).handler(with_param)) // async handler - .resource("/async/{name}", |r| r.async(Method::GET, index_async)) + .resource("/async/{name}", |r| r.route().method(Method::GET).async(index_async)) // redirect - .resource("/", |r| r.handler(Method::GET, |req| { + .resource("/", |r| r.route().method(Method::GET).handler(|req| { println!("{:?}", req); httpcodes::HTTPFound diff --git a/examples/state.rs b/examples/state.rs index 52a2da799..afdc5e78f 100644 --- a/examples/state.rs +++ b/examples/state.rs @@ -64,7 +64,9 @@ fn main() { // enable logger .middleware(middlewares::Logger::default()) // websocket route - .resource("/ws/", |r| r.get(|r| ws::start(r, MyWebSocket{counter: 0}))) + .resource( + "/ws/", |r| r.route().method(Method::GET) + .handler(|req| ws::start(req, MyWebSocket{counter: 0}))) // register simple handler, handle all methods .handler("/", index)) .serve::<_, ()>("127.0.0.1:8080").unwrap(); diff --git a/examples/websocket.rs b/examples/websocket.rs index 655fca05e..0772b3c99 100644 --- a/examples/websocket.rs +++ b/examples/websocket.rs @@ -65,7 +65,7 @@ fn main() { // enable logger .middleware(middlewares::Logger::default()) // websocket route - .resource("/ws/", |r| r.get(ws_index)) + .resource("/ws/", |r| r.route().method(Method::GET).handler(ws_index)) // static files .route("/", fs::StaticFiles::new("examples/static/", true))) // start http server on 127.0.0.1:8080 diff --git a/guide/src/qs_10.md b/guide/src/qs_10.md index 422e0812d..66a049d22 100644 --- a/guide/src/qs_10.md +++ b/guide/src/qs_10.md @@ -50,7 +50,7 @@ INFO:actix_web::middlewares::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800 `%b` Size of response in bytes, including HTTP headers - `%T` Time taken to serve the request, in seconds with floating fraction in .06f format + `%T` Time taken to serve the request, in seconds with floating fraction in .06f format `%D` Time taken to serve the request, in milliseconds @@ -63,7 +63,7 @@ INFO:actix_web::middlewares::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800 ## Default headers -It is possible to set default response headers with `DefaultHeaders` middleware. +Tto set default response headers `DefaultHeaders` middleware could be used. *DefaultHeaders* middleware does not set header if response headers already contains it. ```rust @@ -77,8 +77,8 @@ fn main() { .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(|req| httpcodes::HTTPOk); + r.method(Method::HEAD).handler(|req| httpcodes::HTTPMethodNotAllowed); }) .finish(); } diff --git a/guide/src/qs_12.md b/guide/src/qs_12.md index 102f4f94c..a280e0759 100644 --- a/guide/src/qs_12.md +++ b/guide/src/qs_12.md @@ -16,7 +16,7 @@ fn index(req: HttpRequest) -> Result { fn main() { Application::default("/") - .resource(r"/a/{tail:*}", |r| r.get(index)) + .resource(r"/a/{tail:*}", |r| r.method(Method::GET).handler(index)) .finish(); } ``` diff --git a/guide/src/qs_2.md b/guide/src/qs_2.md index 4fbcf67fa..480aacb86 100644 --- a/guide/src/qs_2.md +++ b/guide/src/qs_2.md @@ -29,22 +29,29 @@ In order to implement a web server, first we need to create a request handler. A request handler is a function that accepts a `HttpRequest` instance as its only parameter and returns a type that can be converted into `HttpResponse`: -```rust,ignore -extern crate actix_web; -use actix_web::*; - -fn index(req: HttpRequest) -> &'static str { - "Hello world!" -} +```rust +# extern crate actix_web; +# use actix_web::*; + fn index(req: HttpRequest) -> &'static str { + "Hello world!" + } +# fn main() {} ``` Next, create an `Application` instance and register the request handler with the application's `resource` on a particular *HTTP method* and *path*:: -```rust,ignore +```rust +# extern crate actix_web; +# use actix_web::*; +# fn index(req: HttpRequest) -> &'static str { +# "Hello world!" +# } +# fn main() { let app = Application::default("/") - .resource("/", |r| r.get(index)) - .finish() + .resource("/", |r| r.method(Method::GET).handler(index)) + .finish(); +# } ``` After that, application instance can be used with `HttpServer` to listen for incoming @@ -73,7 +80,7 @@ fn main() { HttpServer::new( Application::default("/") - .resource("/", |r| r.get(index))) + .resource("/", |r| r.route().handler(index))) .serve::<_, ()>("127.0.0.1:8088").unwrap(); println!("Started http server: 127.0.0.1:8088"); diff --git a/guide/src/qs_3.md b/guide/src/qs_3.md index 66606206e..28841f894 100644 --- a/guide/src/qs_3.md +++ b/guide/src/qs_3.md @@ -13,9 +13,18 @@ Application acts as namespace for all routes, i.e all routes for specific applic has same url path prefix: ```rust,ignore +# extern crate actix_web; +# extern crate tokio_core; +# use actix_web::*; +# fn index(req: HttpRequest) -> &'static str { +# "Hello world!" +# } + +# fn main() { let app = Application::default("/prefix") - .resource("/index.html", |r| r.handler(Method::GET, index) + .resource("/index.html", |r| r.method(Method::GET).handler(index)) .finish() +# } ``` In this example application with `/prefix` prefix and `index.html` resource @@ -24,8 +33,8 @@ get created. This resource is available as on `/prefix/index.html` url. Multiple applications could be served with one server: ```rust -extern crate actix_web; -extern crate tokio_core; +# extern crate actix_web; +# extern crate tokio_core; use std::net::SocketAddr; use actix_web::*; use tokio_core::net::TcpStream; @@ -33,13 +42,13 @@ use tokio_core::net::TcpStream; fn main() { HttpServer::::new(vec![ Application::default("/app1") - .resource("/", |r| r.get(|r| httpcodes::HTTPOk)) + .resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk)) .finish(), Application::default("/app2") - .resource("/", |r| r.get(|r| httpcodes::HTTPOk)) + .resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk)) .finish(), Application::default("/") - .resource("/", |r| r.get(|r| httpcodes::HTTPOk)) + .resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk)) .finish(), ]); } diff --git a/guide/src/qs_4.md b/guide/src/qs_4.md index 1675b3a19..0e0ff981c 100644 --- a/guide/src/qs_4.md +++ b/guide/src/qs_4.md @@ -78,8 +78,8 @@ fn main() { HttpServer::new( Application::default("/") - .resource("/", |r| r.handler( - Method::GET, |req| {MyObj{name: "user".to_owned()}}))) + .resource("/", |r| r.method( + Method::GET).handler(|req| {MyObj{name: "user".to_owned()}}))) .serve::<_, ()>("127.0.0.1:8088").unwrap(); println!("Started http server: 127.0.0.1:8088"); diff --git a/guide/src/qs_5.md b/guide/src/qs_5.md index 849056dc1..4ccceceaf 100644 --- a/guide/src/qs_5.md +++ b/guide/src/qs_5.md @@ -8,14 +8,17 @@ which corresponds to requested URL. Prefix handler: -```rust,ignore -fn index(req: Httprequest) -> HttpResponse { - ... +```rust +# extern crate actix_web; +# use actix_web::*; + +fn index(req: HttpRequest) -> HttpResponse { + unimplemented!() } fn main() { Application::default("/") - .handler("/prefix", |req| index) + .handler("/prefix", index) .finish(); } ``` @@ -24,10 +27,17 @@ In this example `index` get called for any url which starts with `/prefix`. Application prefix combines with handler prefix i.e -```rust,ignore +```rust +# extern crate actix_web; +# use actix_web::*; + +fn index(req: HttpRequest) -> HttpResponse { + unimplemented!() +} + fn main() { Application::default("/app") - .handler("/prefix", |req| index) + .handler("/prefix", index) .finish(); } ``` @@ -38,12 +48,15 @@ Resource contains set of route for same endpoint. Route corresponds to handling *HTTP method* by calling *web handler*. Resource select route based on *http method*, if no route could be matched default response `HTTPMethodNotAllowed` get resturned. -```rust,ignore +```rust +# extern crate actix_web; +# use actix_web::*; + fn main() { Application::default("/") .resource("/prefix", |r| { - r.get(HTTPOk) - r.post(HTTPForbidden) + r.method(Method::GET).handler(|r| httpcodes::HTTPOk); + r.method(Method::POST).handler(|r| httpcodes::HTTPForbidden); }) .finish(); } @@ -65,7 +78,7 @@ used later in a request handler to access the matched value for that part. This done by looking up the identifier in the `HttpRequest.match_info` object: ```rust -extern crate actix_web; +# extern crate actix_web; use actix_web::*; fn index(req: HttpRequest) -> String { @@ -74,7 +87,7 @@ fn index(req: HttpRequest) -> String { fn main() { Application::default("/") - .resource("/{name}", |r| r.get(index)) + .resource("/{name}", |r| r.method(Method::GET).handler(index)) .finish(); } ``` @@ -83,10 +96,16 @@ By default, each part matches the regular expression `[^{}/]+`. You can also specify a custom regex in the form `{identifier:regex}`: -```rust,ignore +```rust +# extern crate actix_web; +# use actix_web::*; +# fn index(req: HttpRequest) -> String { +# format!("Hello, {}", &req.match_info()["name"]) +# } + fn main() { Application::default("/") - .resource(r"{name:\d+}", |r| r.get(index)) + .resource(r"{name:\d+}", |r| r.method(Method::GET).handler(index)) .finish(); } ``` @@ -107,20 +126,19 @@ fn index(req: HttpRequest) -> Result { fn main() { Application::default("/") - .resource(r"/a/{v1}/{v2}/", |r| r.get(index)) + .resource(r"/a/{v1}/{v2}/", |r| r.route().handler(index)) .finish(); } ``` For this example for path '/a/1/2/', values v1 and v2 will resolve to "1" and "2". -To match path tail, `{tail:*}` pattern could be used. Tail pattern must to be last -component of a path, any text after tail pattern will result in panic. +It is possible to match path tail with custom `.*` regex. ```rust,ignore fn main() { Application::default("/") - .resource(r"/test/{tail:*}", |r| r.get(index)) + .resource(r"/test/{tail:.*}", |r| r.method(Method::GET).handler(index)) .finish(); } ``` @@ -142,11 +160,10 @@ an `Err` is returned indicating the condition met: * Percent-encoding results in invalid UTF8. As a result of these conditions, a `PathBuf` parsed from request path parameter is -safe to interpolate within, or use as a suffix of, a path without additional -checks. +safe to interpolate within, or use as a suffix of, a path without additional checks. ```rust -extern crate actix_web; +# extern crate actix_web; use actix_web::*; use std::path::PathBuf; @@ -157,7 +174,7 @@ fn index(req: HttpRequest) -> Result { fn main() { Application::default("/") - .resource(r"/a/{tail:*}", |r| r.get(index)) + .resource(r"/a/{tail:.*}", |r| r.method(Method::GET).handler(index)) .finish(); } ``` diff --git a/guide/src/qs_6.md b/guide/src/qs_6.md index 8060e455a..096459b78 100644 --- a/guide/src/qs_6.md +++ b/guide/src/qs_6.md @@ -30,7 +30,7 @@ fn index(req: HttpRequest) -> String { fn main() { Application::build("/", AppState{counter: Cell::new(0)}) - .resource("/", |r| r.handler(Method::GET, index)) + .resource("/", |r| r.method(Method::GET).handler(index)) .finish(); } ``` diff --git a/guide/src/qs_7.md b/guide/src/qs_7.md index 356c1d817..fcf2dec83 100644 --- a/guide/src/qs_7.md +++ b/guide/src/qs_7.md @@ -54,7 +54,7 @@ fn index(req: HttpRequest) -> Result> { fn main() { Application::default("/") - .resource(r"/a/{name}", |r| r.get(index)) + .resource(r"/a/{name}", |r| r.method(Method::GET).handler(index)) .finish(); } ``` diff --git a/src/application.rs b/src/application.rs index 91514d151..3e05487e0 100644 --- a/src/application.rs +++ b/src/application.rs @@ -118,7 +118,7 @@ impl ApplicationBuilder 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 ApplicationBuilder 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(); /// } diff --git a/src/lib.rs b/src/lib.rs index 6b90a3917..cc69995ad 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/middlewares/defaultheaders.rs b/src/middlewares/defaultheaders.rs index ae52e684f..cf2503e30 100644 --- a/src/middlewares/defaultheaders.rs +++ b/src/middlewares/defaultheaders.rs @@ -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(); /// } diff --git a/src/pred.rs b/src/pred.rs new file mode 100644 index 000000000..2eebd040d --- /dev/null +++ b/src/pred.rs @@ -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 { + + /// Check if request matches predicate + fn check(&self, &mut HttpRequest) -> bool; + +} + +/// Return predicate that matches if any of supplied predicate matches. +pub fn Any(preds: T) -> Box> + where T: IntoIterator>> +{ + Box::new(AnyPredicate(preds.into_iter().collect())) +} + +struct AnyPredicate(Vec>>); + +impl Predicate for AnyPredicate { + fn check(&self, req: &mut HttpRequest) -> 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(preds: T) -> Box> + where T: IntoIterator>> +{ + Box::new(AllPredicate(preds.into_iter().collect())) +} + +struct AllPredicate(Vec>>); + +impl Predicate for AllPredicate { + fn check(&self, req: &mut HttpRequest) -> 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(pred: Box>) -> Box> +{ + Box::new(NotPredicate(pred)) +} + +struct NotPredicate(Box>); + +impl Predicate for NotPredicate { + fn check(&self, req: &mut HttpRequest) -> bool { + !self.0.check(req) + } +} + +/// Http method predicate +struct MethodPredicate(http::Method, PhantomData); + +impl Predicate for MethodPredicate { + fn check(&self, req: &mut HttpRequest) -> bool { + *req.method() == self.0 + } +} + +/// Predicate to match *GET* http method +pub fn Get() -> Box> { + Box::new(MethodPredicate(http::Method::GET, PhantomData)) +} + +/// Predicate to match *POST* http method +pub fn Post() -> Box> { + Box::new(MethodPredicate(http::Method::POST, PhantomData)) +} + +/// Predicate to match *PUT* http method +pub fn Put() -> Box> { + Box::new(MethodPredicate(http::Method::PUT, PhantomData)) +} + +/// Predicate to match *DELETE* http method +pub fn Delete() -> Box> { + Box::new(MethodPredicate(http::Method::DELETE, PhantomData)) +} + +/// Predicate to match *HEAD* http method +pub fn Head() -> Box> { + Box::new(MethodPredicate(http::Method::HEAD, PhantomData)) +} + +/// Predicate to match *OPTIONS* http method +pub fn Options() -> Box> { + Box::new(MethodPredicate(http::Method::OPTIONS, PhantomData)) +} + +/// Predicate to match *CONNECT* http method +pub fn Connect() -> Box> { + Box::new(MethodPredicate(http::Method::CONNECT, PhantomData)) +} + +/// Predicate to match *PATCH* http method +pub fn Patch() -> Box> { + Box::new(MethodPredicate(http::Method::PATCH, PhantomData)) +} + +/// Predicate to match *TRACE* http method +pub fn Trace() -> Box> { + Box::new(MethodPredicate(http::Method::TRACE, PhantomData)) +} + +/// Predicate to match specified http method +pub fn Method(method: http::Method) -> Box> { + Box::new(MethodPredicate(method, PhantomData)) +} + +/// Return predicate that matches if request contains specified header and value. +pub fn Header(name: &'static str, value: &'static str) -> Box> +{ + Box::new(HeaderPredicate(header::HeaderName::try_from(name).unwrap(), + header::HeaderValue::from_static(value), + PhantomData)) +} + +struct HeaderPredicate(header::HeaderName, header::HeaderValue, PhantomData); + +impl Predicate for HeaderPredicate { + fn check(&self, req: &mut HttpRequest) -> bool { + if let Some(val) = req.headers().get(&self.0) { + return val == self.1 + } + false + } +} diff --git a/src/recognizer.rs b/src/recognizer.rs index 7531b43aa..aa17c9d7a 100644 --- a/src/recognizer.rs +++ b/src/recognizer.rs @@ -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 { /// let ivalue: isize = req.match_info().query("val")?; - /// format!("isuze value: {:?}", ivalue) + /// Ok(format!("isuze value: {:?}", ivalue)) /// } + /// # fn main() {} /// ``` pub fn query(&self, key: &str) -> Result::Err> { diff --git a/src/resource.rs b/src/resource.rs index b13fda249..c175b683f 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -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 { + preds: Vec>>, + handler: Box>, +} + +impl Default for Route { + + fn default() -> Route { + Route { + preds: Vec::new(), + handler: Box::new(WrapHandler::new(|_| HTTPNotFound)), + } + } +} + +impl Route { + + fn check(&self, req: &mut HttpRequest) -> bool { + for pred in &self.preds { + if !pred.check(req) { + return false + } + } + true + } + + fn handle(&self, req: HttpRequest) -> Reply { + self.handler.handle(req) + } + + /// Add match predicate to route. + pub fn p(&mut self, p: Box>) -> &mut Self { + self.preds.push(p); + self + } + + /// Add predicates to route. + pub fn predicates

(&mut self, preds: P) -> &mut Self + where P: IntoIterator>> + { + 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(&mut self, handler: F) + where F: Fn(HttpRequest) -> R + 'static, + R: FromRequest + 'static, + { + self.handler = Box::new(WrapHandler::new(handler)); + } + + /// Set handler function. + pub fn async(&mut self, handler: F) + where F: Fn(HttpRequest) -> R + 'static, + R: Future + '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 { name: String, state: PhantomData, - routes: HashMap>>, + routes: Vec>, default: Box>, } @@ -37,8 +114,8 @@ impl Default for Resource { 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 Resource where S: 'static { Resource { name: String::new(), state: PhantomData, - routes: HashMap::new(), + routes: Vec::new(), default: Box::new(HTTPNotFound)} } @@ -57,65 +134,48 @@ impl Resource where S: 'static { self.name = name.into(); } - /// Register handler for specified method. - pub fn handler(&mut self, method: Method, handler: F) - where F: Fn(HttpRequest) -> 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 { + self.routes.push(Route::default()); + self.routes.last_mut().unwrap() } - /// Register async handler for specified method. - pub fn async(&mut self, method: Method, handler: F) - where F: Fn(HttpRequest) -> R + 'static, - R: Future + '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 { + 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(&mut self, handler: H) where H: Handler - { + /// By default `HTTPNotFound` is used. + pub fn default_handler(&mut self, handler: H) where H: Handler { self.default = Box::new(WrapHandler::new(handler)); } - - /// Register handler for `GET` method. - pub fn get(&mut self, handler: F) - where F: Fn(HttpRequest) -> R + 'static, - R: FromRequest + 'static, { - self.routes.insert(Method::GET, Box::new(WrapHandler::new(handler))); - } - - /// Register handler for `POST` method. - pub fn post(&mut self, handler: F) - where F: Fn(HttpRequest) -> R + 'static, - R: FromRequest + 'static, { - self.routes.insert(Method::POST, Box::new(WrapHandler::new(handler))); - } - - /// Register handler for `PUT` method. - pub fn put(&mut self, handler: F) - where F: Fn(HttpRequest) -> R + 'static, - R: FromRequest + 'static, { - self.routes.insert(Method::PUT, Box::new(WrapHandler::new(handler))); - } - - /// Register handler for `DELETE` method. - pub fn delete(&mut self, handler: F) - where F: Fn(HttpRequest) -> R + 'static, - R: FromRequest + 'static, { - self.routes.insert(Method::DELETE, Box::new(WrapHandler::new(handler))); - } } impl RouteHandler for Resource { - fn handle(&self, req: HttpRequest) -> Reply { - if let Some(handler) = self.routes.get(req.method()) { - handler.handle(req) - } else { - self.default.handle(req) + fn handle(&self, mut req: HttpRequest) -> Reply { + for route in &self.routes { + if route.check(&mut req) { + return route.handle(req) + } } + self.default.handle(req) } } diff --git a/src/ws.rs b/src/ws.rs index cd9cf0059..e5e467e07 100644 --- a/src/ws.rs +++ b/src/ws.rs @@ -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(); //! } //! ``` diff --git a/tests/test_server.rs b/tests/test_server.rs index 445536dd4..5cd556c3b 100644 --- a/tests/test_server.rs +++ b/tests/test_server.rs @@ -16,7 +16,7 @@ fn create_server() -> HttpServer> { HttpServer::new( vec![Application::default("/") .resource("/", |r| - r.handler(Method::GET, |_| httpcodes::HTTPOk)) + r.route().method(Method::GET).handler(|_| httpcodes::HTTPOk)) .finish()]) } @@ -94,7 +94,7 @@ fn test_middlewares() { response: act_num2, finish: act_num3}) .resource("/", |r| - r.handler(Method::GET, |_| httpcodes::HTTPOk)) + r.route().method(Method::GET).handler(|_| httpcodes::HTTPOk)) .finish()]) .serve::<_, ()>("127.0.0.1:58904").unwrap(); sys.run();