1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-06-25 06:39:22 +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

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