mirror of
https://github.com/actix/actix-web.git
synced 2024-11-26 19:41:12 +00:00
introduce route predicates
This commit is contained in:
parent
57fd35ffc1
commit
3bf3738e65
20 changed files with 370 additions and 122 deletions
|
@ -108,7 +108,8 @@ fn main() {
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.middleware(middlewares::Logger::default()) // <- register logger middleware
|
.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
|
.route("/", fs::StaticFiles::new("examples/static/", true))) // <- serve static files
|
||||||
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
||||||
|
|
||||||
|
|
|
@ -69,11 +69,11 @@ fn main() {
|
||||||
// register simple handle r, handle all methods
|
// register simple handle r, handle all methods
|
||||||
.handler("/index.html", index)
|
.handler("/index.html", index)
|
||||||
// with path parameters
|
// 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
|
// 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
|
// redirect
|
||||||
.resource("/", |r| r.handler(Method::GET, |req| {
|
.resource("/", |r| r.route().method(Method::GET).handler(|req| {
|
||||||
println!("{:?}", req);
|
println!("{:?}", req);
|
||||||
|
|
||||||
httpcodes::HTTPFound
|
httpcodes::HTTPFound
|
||||||
|
|
|
@ -64,7 +64,9 @@ fn main() {
|
||||||
// enable logger
|
// enable logger
|
||||||
.middleware(middlewares::Logger::default())
|
.middleware(middlewares::Logger::default())
|
||||||
// websocket route
|
// 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
|
// register simple handler, handle all methods
|
||||||
.handler("/", index))
|
.handler("/", index))
|
||||||
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
.serve::<_, ()>("127.0.0.1:8080").unwrap();
|
||||||
|
|
|
@ -65,7 +65,7 @@ fn main() {
|
||||||
// enable logger
|
// enable logger
|
||||||
.middleware(middlewares::Logger::default())
|
.middleware(middlewares::Logger::default())
|
||||||
// websocket route
|
// websocket route
|
||||||
.resource("/ws/", |r| r.get(ws_index))
|
.resource("/ws/", |r| r.route().method(Method::GET).handler(ws_index))
|
||||||
// static files
|
// static files
|
||||||
.route("/", fs::StaticFiles::new("examples/static/", true)))
|
.route("/", fs::StaticFiles::new("examples/static/", true)))
|
||||||
// start http server on 127.0.0.1:8080
|
// start http server on 127.0.0.1:8080
|
||||||
|
|
|
@ -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
|
`%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
|
`%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
|
## 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.
|
*DefaultHeaders* middleware does not set header if response headers already contains it.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
|
@ -77,8 +77,8 @@ fn main() {
|
||||||
.header("X-Version", "0.2")
|
.header("X-Version", "0.2")
|
||||||
.finish())
|
.finish())
|
||||||
.resource("/test", |r| {
|
.resource("/test", |r| {
|
||||||
r.get(|req| httpcodes::HTTPOk);
|
r.method(Method::GET).handler(|req| httpcodes::HTTPOk);
|
||||||
r.handler(Method::HEAD, |req| httpcodes::HTTPMethodNotAllowed);
|
r.method(Method::HEAD).handler(|req| httpcodes::HTTPMethodNotAllowed);
|
||||||
})
|
})
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,7 +16,7 @@ fn index(req: HttpRequest) -> Result<fs::NamedFile> {
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{tail:*}", |r| r.get(index))
|
.resource(r"/a/{tail:*}", |r| r.method(Method::GET).handler(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
@ -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
|
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`:
|
and returns a type that can be converted into `HttpResponse`:
|
||||||
|
|
||||||
```rust,ignore
|
```rust
|
||||||
extern crate actix_web;
|
# extern crate actix_web;
|
||||||
use actix_web::*;
|
# use actix_web::*;
|
||||||
|
fn index(req: HttpRequest) -> &'static str {
|
||||||
fn index(req: HttpRequest) -> &'static str {
|
"Hello world!"
|
||||||
"Hello world!"
|
}
|
||||||
}
|
# fn main() {}
|
||||||
```
|
```
|
||||||
|
|
||||||
Next, create an `Application` instance and register the
|
Next, create an `Application` instance and register the
|
||||||
request handler with the application's `resource` on a particular *HTTP method* and *path*::
|
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("/")
|
let app = Application::default("/")
|
||||||
.resource("/", |r| r.get(index))
|
.resource("/", |r| r.method(Method::GET).handler(index))
|
||||||
.finish()
|
.finish();
|
||||||
|
# }
|
||||||
```
|
```
|
||||||
|
|
||||||
After that, application instance can be used with `HttpServer` to listen for incoming
|
After that, application instance can be used with `HttpServer` to listen for incoming
|
||||||
|
@ -73,7 +80,7 @@ fn main() {
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/", |r| r.get(index)))
|
.resource("/", |r| r.route().handler(index)))
|
||||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||||
|
|
||||||
println!("Started http server: 127.0.0.1:8088");
|
println!("Started http server: 127.0.0.1:8088");
|
||||||
|
|
|
@ -13,9 +13,18 @@ Application acts as namespace for all routes, i.e all routes for specific applic
|
||||||
has same url path prefix:
|
has same url path prefix:
|
||||||
|
|
||||||
```rust,ignore
|
```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")
|
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()
|
.finish()
|
||||||
|
# }
|
||||||
```
|
```
|
||||||
|
|
||||||
In this example application with `/prefix` prefix and `index.html` resource
|
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:
|
Multiple applications could be served with one server:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
extern crate actix_web;
|
# extern crate actix_web;
|
||||||
extern crate tokio_core;
|
# extern crate tokio_core;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use actix_web::*;
|
use actix_web::*;
|
||||||
use tokio_core::net::TcpStream;
|
use tokio_core::net::TcpStream;
|
||||||
|
@ -33,13 +42,13 @@ use tokio_core::net::TcpStream;
|
||||||
fn main() {
|
fn main() {
|
||||||
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
HttpServer::<TcpStream, SocketAddr, _>::new(vec![
|
||||||
Application::default("/app1")
|
Application::default("/app1")
|
||||||
.resource("/", |r| r.get(|r| httpcodes::HTTPOk))
|
.resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk))
|
||||||
.finish(),
|
.finish(),
|
||||||
Application::default("/app2")
|
Application::default("/app2")
|
||||||
.resource("/", |r| r.get(|r| httpcodes::HTTPOk))
|
.resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk))
|
||||||
.finish(),
|
.finish(),
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/", |r| r.get(|r| httpcodes::HTTPOk))
|
.resource("/", |r| r.route().handler(|r| httpcodes::HTTPOk))
|
||||||
.finish(),
|
.finish(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
|
@ -78,8 +78,8 @@ fn main() {
|
||||||
|
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/", |r| r.handler(
|
.resource("/", |r| r.method(
|
||||||
Method::GET, |req| {MyObj{name: "user".to_owned()}})))
|
Method::GET).handler(|req| {MyObj{name: "user".to_owned()}})))
|
||||||
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
.serve::<_, ()>("127.0.0.1:8088").unwrap();
|
||||||
|
|
||||||
println!("Started http server: 127.0.0.1:8088");
|
println!("Started http server: 127.0.0.1:8088");
|
||||||
|
|
|
@ -8,14 +8,17 @@ which corresponds to requested URL.
|
||||||
|
|
||||||
Prefix handler:
|
Prefix handler:
|
||||||
|
|
||||||
```rust,ignore
|
```rust
|
||||||
fn index(req: Httprequest) -> HttpResponse {
|
# extern crate actix_web;
|
||||||
...
|
# use actix_web::*;
|
||||||
|
|
||||||
|
fn index(req: HttpRequest) -> HttpResponse {
|
||||||
|
unimplemented!()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.handler("/prefix", |req| index)
|
.handler("/prefix", index)
|
||||||
.finish();
|
.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
|
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() {
|
fn main() {
|
||||||
Application::default("/app")
|
Application::default("/app")
|
||||||
.handler("/prefix", |req| index)
|
.handler("/prefix", index)
|
||||||
.finish();
|
.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*,
|
*HTTP method* by calling *web handler*. Resource select route based on *http method*,
|
||||||
if no route could be matched default response `HTTPMethodNotAllowed` get resturned.
|
if no route could be matched default response `HTTPMethodNotAllowed` get resturned.
|
||||||
|
|
||||||
```rust,ignore
|
```rust
|
||||||
|
# extern crate actix_web;
|
||||||
|
# use actix_web::*;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/prefix", |r| {
|
.resource("/prefix", |r| {
|
||||||
r.get(HTTPOk)
|
r.method(Method::GET).handler(|r| httpcodes::HTTPOk);
|
||||||
r.post(HTTPForbidden)
|
r.method(Method::POST).handler(|r| httpcodes::HTTPForbidden);
|
||||||
})
|
})
|
||||||
.finish();
|
.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:
|
done by looking up the identifier in the `HttpRequest.match_info` object:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
extern crate actix_web;
|
# extern crate actix_web;
|
||||||
use actix_web::*;
|
use actix_web::*;
|
||||||
|
|
||||||
fn index(req: HttpRequest) -> String {
|
fn index(req: HttpRequest) -> String {
|
||||||
|
@ -74,7 +87,7 @@ fn index(req: HttpRequest) -> String {
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource("/{name}", |r| r.get(index))
|
.resource("/{name}", |r| r.method(Method::GET).handler(index))
|
||||||
.finish();
|
.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}`:
|
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() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"{name:\d+}", |r| r.get(index))
|
.resource(r"{name:\d+}", |r| r.method(Method::GET).handler(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -107,20 +126,19 @@ fn index(req: HttpRequest) -> Result<String> {
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{v1}/{v2}/", |r| r.get(index))
|
.resource(r"/a/{v1}/{v2}/", |r| r.route().handler(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
For this example for path '/a/1/2/', values v1 and v2 will resolve to "1" and "2".
|
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
|
It is possible to match path tail with custom `.*` regex.
|
||||||
component of a path, any text after tail pattern will result in panic.
|
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/test/{tail:*}", |r| r.get(index))
|
.resource(r"/test/{tail:.*}", |r| r.method(Method::GET).handler(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -142,11 +160,10 @@ an `Err` is returned indicating the condition met:
|
||||||
* Percent-encoding results in invalid UTF8.
|
* Percent-encoding results in invalid UTF8.
|
||||||
|
|
||||||
As a result of these conditions, a `PathBuf` parsed from request path parameter is
|
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
|
safe to interpolate within, or use as a suffix of, a path without additional checks.
|
||||||
checks.
|
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
extern crate actix_web;
|
# extern crate actix_web;
|
||||||
use actix_web::*;
|
use actix_web::*;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
@ -157,7 +174,7 @@ fn index(req: HttpRequest) -> Result<String> {
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{tail:*}", |r| r.get(index))
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).handler(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
@ -30,7 +30,7 @@ fn index(req: HttpRequest<AppState>) -> String {
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::build("/", AppState{counter: Cell::new(0)})
|
Application::build("/", AppState{counter: Cell::new(0)})
|
||||||
.resource("/", |r| r.handler(Method::GET, index))
|
.resource("/", |r| r.method(Method::GET).handler(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
@ -54,7 +54,7 @@ fn index(req: HttpRequest) -> Result<Json<MyObj>> {
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
Application::default("/")
|
Application::default("/")
|
||||||
.resource(r"/a/{name}", |r| r.get(index))
|
.resource(r"/a/{name}", |r| r.method(Method::GET).handler(index))
|
||||||
.finish();
|
.finish();
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
@ -118,7 +118,7 @@ impl<S> ApplicationBuilder<S> where S: 'static {
|
||||||
/// A variable part is specified in the form `{identifier}`, where
|
/// A variable part is specified in the form `{identifier}`, where
|
||||||
/// the identifier can be used later in a request handler to access the matched
|
/// 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
|
/// 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 `[^{}/]+`.
|
/// By default, each part matches the regular expression `[^{}/]+`.
|
||||||
///
|
///
|
||||||
|
@ -134,8 +134,8 @@ impl<S> ApplicationBuilder<S> where S: 'static {
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = Application::default("/")
|
/// let app = Application::default("/")
|
||||||
/// .resource("/test", |r| {
|
/// .resource("/test", |r| {
|
||||||
/// r.get(|req| httpcodes::HTTPOk);
|
/// r.method(Method::GET).handler(|_| httpcodes::HTTPOk);
|
||||||
/// r.handler(Method::HEAD, |req| httpcodes::HTTPMethodNotAllowed);
|
/// r.method(Method::HEAD).handler(|_| httpcodes::HTTPMethodNotAllowed);
|
||||||
/// })
|
/// })
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
|
|
|
@ -75,6 +75,7 @@ pub mod error;
|
||||||
pub mod httpcodes;
|
pub mod httpcodes;
|
||||||
pub mod multipart;
|
pub mod multipart;
|
||||||
pub mod middlewares;
|
pub mod middlewares;
|
||||||
|
pub mod pred;
|
||||||
pub use error::{Error, Result};
|
pub use error::{Error, Result};
|
||||||
pub use encoding::ContentEncoding;
|
pub use encoding::ContentEncoding;
|
||||||
pub use body::{Body, Binary};
|
pub use body::{Body, Binary};
|
||||||
|
@ -83,7 +84,7 @@ pub use httprequest::{HttpRequest, UrlEncoded};
|
||||||
pub use httpresponse::HttpResponse;
|
pub use httpresponse::HttpResponse;
|
||||||
pub use payload::{Payload, PayloadItem};
|
pub use payload::{Payload, PayloadItem};
|
||||||
pub use route::{Reply, Json, FromRequest};
|
pub use route::{Reply, Json, FromRequest};
|
||||||
pub use resource::Resource;
|
pub use resource::{Route, Resource};
|
||||||
pub use recognizer::Params;
|
pub use recognizer::Params;
|
||||||
pub use server::HttpServer;
|
pub use server::HttpServer;
|
||||||
pub use context::HttpContext;
|
pub use context::HttpContext;
|
||||||
|
|
|
@ -21,8 +21,8 @@ use middlewares::{Response, Middleware};
|
||||||
/// .header("X-Version", "0.2")
|
/// .header("X-Version", "0.2")
|
||||||
/// .finish())
|
/// .finish())
|
||||||
/// .resource("/test", |r| {
|
/// .resource("/test", |r| {
|
||||||
/// r.get(|req| httpcodes::HTTPOk);
|
/// r.method(Method::GET).handler(|_| httpcodes::HTTPOk);
|
||||||
/// r.handler(Method::HEAD, |req| httpcodes::HTTPMethodNotAllowed);
|
/// r.method(Method::HEAD).handler(|_| httpcodes::HTTPMethodNotAllowed);
|
||||||
/// })
|
/// })
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
|
|
148
src/pred.rs
Normal file
148
src/pred.rs
Normal 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
|
||||||
|
}
|
||||||
|
}
|
|
@ -76,11 +76,14 @@ impl Params {
|
||||||
///
|
///
|
||||||
/// If keyed parameter is not available empty string is used as default value.
|
/// If keyed parameter is not available empty string is used as default value.
|
||||||
///
|
///
|
||||||
/// ```rust,ignore
|
/// ```rust
|
||||||
/// fn index(req: HttpRequest) -> String {
|
/// # extern crate actix_web;
|
||||||
|
/// # use actix_web::*;
|
||||||
|
/// fn index(req: HttpRequest) -> Result<String> {
|
||||||
/// let ivalue: isize = req.match_info().query("val")?;
|
/// 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>
|
pub fn query<T: FromParam>(&self, key: &str) -> Result<T, <T as FromParam>::Err>
|
||||||
{
|
{
|
||||||
|
|
174
src/resource.rs
174
src/resource.rs
|
@ -1,34 +1,111 @@
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use http::Method;
|
use http::Method;
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
|
|
||||||
use error::Error;
|
use error::Error;
|
||||||
|
use pred::{self, Predicate};
|
||||||
use route::{Reply, Handler, FromRequest, RouteHandler, AsyncHandler, WrapHandler};
|
use route::{Reply, Handler, FromRequest, RouteHandler, AsyncHandler, WrapHandler};
|
||||||
|
use httpcodes::HTTPNotFound;
|
||||||
use httprequest::HttpRequest;
|
use httprequest::HttpRequest;
|
||||||
use httpresponse::HttpResponse;
|
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
|
/// Http resource
|
||||||
///
|
///
|
||||||
/// `Resource` is an entry in route table which corresponds to requested URL.
|
/// `Resource` is an entry in route table which corresponds to requested URL.
|
||||||
///
|
///
|
||||||
/// Resource in turn has at least one route.
|
/// 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
|
/// ```rust
|
||||||
/// extern crate actix_web;
|
/// extern crate actix_web;
|
||||||
|
/// use actix_web::*;
|
||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = actix_web::Application::default("/")
|
/// let app = Application::default("/")
|
||||||
/// .resource("/", |r| r.get(|_| actix_web::HttpResponse::Ok()))
|
/// .resource(
|
||||||
|
/// "/", |r| r.route().method(Method::GET).handler(|r| HttpResponse::Ok()))
|
||||||
/// .finish();
|
/// .finish();
|
||||||
/// }
|
/// }
|
||||||
pub struct Resource<S=()> {
|
pub struct Resource<S=()> {
|
||||||
name: String,
|
name: String,
|
||||||
state: PhantomData<S>,
|
state: PhantomData<S>,
|
||||||
routes: HashMap<Method, Box<RouteHandler<S>>>,
|
routes: Vec<Route<S>>,
|
||||||
default: Box<RouteHandler<S>>,
|
default: Box<RouteHandler<S>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -37,8 +114,8 @@ impl<S> Default for Resource<S> {
|
||||||
Resource {
|
Resource {
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
state: PhantomData,
|
state: PhantomData,
|
||||||
routes: HashMap::new(),
|
routes: Vec::new(),
|
||||||
default: Box::new(HTTPMethodNotAllowed)}
|
default: Box::new(HTTPNotFound)}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -48,7 +125,7 @@ impl<S> Resource<S> where S: 'static {
|
||||||
Resource {
|
Resource {
|
||||||
name: String::new(),
|
name: String::new(),
|
||||||
state: PhantomData,
|
state: PhantomData,
|
||||||
routes: HashMap::new(),
|
routes: Vec::new(),
|
||||||
default: Box::new(HTTPNotFound)}
|
default: Box::new(HTTPNotFound)}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -57,65 +134,48 @@ impl<S> Resource<S> where S: 'static {
|
||||||
self.name = name.into();
|
self.name = name.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register handler for specified method.
|
/// Register a new route and return mutable reference to *Route* object.
|
||||||
pub fn handler<F, R>(&mut self, method: Method, handler: F)
|
/// *Route* is used for route configuration, i.e. adding predicates, setting up handler.
|
||||||
where F: Fn(HttpRequest<S>) -> R + 'static,
|
///
|
||||||
R: FromRequest + 'static,
|
/// ```rust
|
||||||
{
|
/// extern crate actix_web;
|
||||||
self.routes.insert(method, Box::new(WrapHandler::new(handler)));
|
/// 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.
|
/// Register a new route and add method check to route.
|
||||||
pub fn async<F, R>(&mut self, method: Method, handler: F)
|
pub fn method(&mut self, method: Method) -> &mut Route<S> {
|
||||||
where F: Fn(HttpRequest<S>) -> R + 'static,
|
self.routes.push(Route::default());
|
||||||
R: Future<Item=HttpResponse, Error=Error> + 'static,
|
self.routes.last_mut().unwrap().method(method)
|
||||||
{
|
|
||||||
self.routes.insert(method, Box::new(AsyncHandler::new(handler)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Default handler is used if no matched route found.
|
/// Default handler is used if no matched route found.
|
||||||
/// By default `HTTPMethodNotAllowed` is used.
|
/// By default `HTTPNotFound` is used.
|
||||||
pub fn default_handler<H>(&mut self, handler: H) where H: Handler<S>
|
pub fn default_handler<H>(&mut self, handler: H) where H: Handler<S> {
|
||||||
{
|
|
||||||
self.default = Box::new(WrapHandler::new(handler));
|
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> {
|
impl<S: 'static> RouteHandler<S> for Resource<S> {
|
||||||
|
|
||||||
fn handle(&self, req: HttpRequest<S>) -> Reply {
|
fn handle(&self, mut req: HttpRequest<S>) -> Reply {
|
||||||
if let Some(handler) = self.routes.get(req.method()) {
|
for route in &self.routes {
|
||||||
handler.handle(req)
|
if route.check(&mut req) {
|
||||||
} else {
|
return route.handle(req)
|
||||||
self.default.handle(req)
|
}
|
||||||
}
|
}
|
||||||
|
self.default.handle(req)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -43,7 +43,7 @@
|
||||||
//!
|
//!
|
||||||
//! fn main() {
|
//! fn main() {
|
||||||
//! Application::default("/")
|
//! 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();
|
//! .finish();
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
|
|
@ -16,7 +16,7 @@ fn create_server<T, A>() -> HttpServer<T, A, Application<()>> {
|
||||||
HttpServer::new(
|
HttpServer::new(
|
||||||
vec![Application::default("/")
|
vec![Application::default("/")
|
||||||
.resource("/", |r|
|
.resource("/", |r|
|
||||||
r.handler(Method::GET, |_| httpcodes::HTTPOk))
|
r.route().method(Method::GET).handler(|_| httpcodes::HTTPOk))
|
||||||
.finish()])
|
.finish()])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -94,7 +94,7 @@ fn test_middlewares() {
|
||||||
response: act_num2,
|
response: act_num2,
|
||||||
finish: act_num3})
|
finish: act_num3})
|
||||||
.resource("/", |r|
|
.resource("/", |r|
|
||||||
r.handler(Method::GET, |_| httpcodes::HTTPOk))
|
r.route().method(Method::GET).handler(|_| httpcodes::HTTPOk))
|
||||||
.finish()])
|
.finish()])
|
||||||
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
.serve::<_, ()>("127.0.0.1:58904").unwrap();
|
||||||
sys.run();
|
sys.run();
|
||||||
|
|
Loading…
Reference in a new issue