1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 07:53:00 +01: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

@ -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();

View File

@ -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

View File

@ -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();

View File

@ -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

View File

@ -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();
}

View File

@ -16,7 +16,7 @@ fn index(req: HttpRequest) -> Result<fs::NamedFile> {
fn main() {
Application::default("/")
.resource(r"/a/{tail:*}", |r| r.get(index))
.resource(r"/a/{tail:*}", |r| r.method(Method::GET).handler(index))
.finish();
}
```

View File

@ -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");

View File

@ -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::<TcpStream, SocketAddr, _>::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(),
]);
}

View File

@ -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");

View File

@ -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<String> {
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<String> {
fn main() {
Application::default("/")
.resource(r"/a/{tail:*}", |r| r.get(index))
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).handler(index))
.finish();
}
```

View File

@ -30,7 +30,7 @@ fn index(req: HttpRequest<AppState>) -> 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();
}
```

View File

@ -54,7 +54,7 @@ fn index(req: HttpRequest) -> Result<Json<MyObj>> {
fn main() {
Application::default("/")
.resource(r"/a/{name}", |r| r.get(index))
.resource(r"/a/{name}", |r| r.method(Method::GET).handler(index))
.finish();
}
```

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();
//! }
//! ```

View File

@ -16,7 +16,7 @@ fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
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();