2017-12-11 23:16:29 +01:00
|
|
|
# URL Dispatch
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
URL dispatch provides a simple way for mapping URLs to `Handler` code using a simple pattern
|
|
|
|
matching language. If one of the patterns matches the path information associated with a request,
|
|
|
|
a particular handler object is invoked. A handler is a specific object that implements the
|
2017-12-30 21:13:23 +01:00
|
|
|
`Handler` trait, defined in your application, that receives the request and returns
|
2018-03-28 22:16:01 +02:00
|
|
|
a response object. More information is available in the [handler section](../qs_4.html).
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
## Resource configuration
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
Resource configuration is the act of adding a new resources to an application.
|
2017-12-30 21:13:23 +01:00
|
|
|
A resource has a name, which acts as an identifier to be used for URL generation.
|
|
|
|
The name also allows developers to add routes to existing resources.
|
2017-12-25 17:12:13 +01:00
|
|
|
A resource also has a pattern, meant to match against the *PATH* portion of a *URL*,
|
2018-03-28 22:16:01 +02:00
|
|
|
it does not match against the *QUERY* portion (the portion following the scheme and
|
2017-12-25 17:12:13 +01:00
|
|
|
port, e.g., */foo/bar* in the *URL* *http://localhost:8080/foo/bar?q=value*).
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
The [Application::resource](../actix_web/struct.Application.html#method.resource) methods
|
2018-03-28 22:16:01 +02:00
|
|
|
add a single resource to application routing table. This method accepts a *path pattern*
|
|
|
|
and a resource configuration function.
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-04 22:32:05 +01:00
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
2018-03-31 02:31:18 +02:00
|
|
|
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
|
2017-12-30 21:13:23 +01:00
|
|
|
#
|
2017-12-11 23:16:29 +01:00
|
|
|
# fn index(req: HttpRequest) -> HttpResponse {
|
|
|
|
# unimplemented!()
|
|
|
|
# }
|
2017-12-30 21:13:23 +01:00
|
|
|
#
|
2017-12-02 08:42:21 +01:00
|
|
|
fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
Application::new()
|
2017-12-06 17:03:08 +01:00
|
|
|
.resource("/prefix", |r| r.f(index))
|
2017-12-30 21:13:23 +01:00
|
|
|
.resource("/user/{name}",
|
2018-03-31 08:07:33 +02:00
|
|
|
|r| r.method(Method::GET).f(|req| HttpResponse::Ok()))
|
2017-12-02 08:42:21 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
The *Configuration function* has the following type:
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
```rust,ignore
|
|
|
|
FnOnce(&mut Resource<_>) -> ()
|
|
|
|
```
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
The *Configuration function* can set a name and register specific routes.
|
|
|
|
If a resource does not contain any route or does not have any matching routes it
|
|
|
|
returns *NOT FOUND* http response.
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
## Configuring a Route
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
Resource contains a set of routes. Each route in turn has a set of predicates and a handler.
|
|
|
|
New routes can be created with `Resource::route()` method which returns a reference
|
|
|
|
to new *Route* instance. By default the *route* does not contain any predicates, so matches
|
|
|
|
all requests and the default handler is `HttpNotFound`.
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
The application routes incoming requests based on route criteria which are defined during
|
2017-12-11 23:16:29 +01:00
|
|
|
resource registration and route registration. Resource matches all routes it contains in
|
2018-03-28 22:16:01 +02:00
|
|
|
the order the routes were registered via `Resource::route()`. A *Route* can contain
|
2017-12-11 23:16:29 +01:00
|
|
|
any number of *predicates* but only one handler.
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-04 22:32:05 +01:00
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
|
|
|
# use actix_web::*;
|
|
|
|
|
2017-12-02 08:42:21 +01:00
|
|
|
fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
Application::new()
|
|
|
|
.resource("/path", |resource|
|
|
|
|
resource.route()
|
2018-03-02 03:32:31 +01:00
|
|
|
.filter(pred::Get())
|
|
|
|
.filter(pred::Header("content-type", "text/plain"))
|
2018-03-31 08:07:33 +02:00
|
|
|
.f(|req| HttpResponse::Ok())
|
2017-12-11 23:16:29 +01:00
|
|
|
)
|
2017-12-02 08:42:21 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-03-31 08:07:33 +02:00
|
|
|
In this example `HttpResponse::Ok()` is returned for *GET* requests,
|
2017-12-11 23:16:29 +01:00
|
|
|
if request contains `Content-Type` header and value of this header is *text/plain*
|
2018-03-28 22:16:01 +02:00
|
|
|
and path equals to `/path`. Resource calls handle of the first matching route.
|
|
|
|
If a resource can not match any route a "NOT FOUND" response is returned.
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
[*Resource::route()*](../actix_web/struct.Resource.html#method.route) returns a
|
|
|
|
[*Route*](../actix_web/struct.Route.html) object. Route can be configured with a
|
2017-12-20 07:36:06 +01:00
|
|
|
builder-like pattern. Following configuration methods are available:
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
* [*Route::filter()*](../actix_web/struct.Route.html#method.filter) registers a new predicate.
|
|
|
|
Any number of predicates can be registered for each route.
|
2017-12-30 21:13:23 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
* [*Route::f()*](../actix_web/struct.Route.html#method.f) registers handler function
|
|
|
|
for this route. Only one handler can be registered. Usually handler registration
|
|
|
|
is the last config operation. Handler function can be a function or closure and has the type
|
2017-12-20 07:36:06 +01:00
|
|
|
`Fn(HttpRequest<S>) -> R + 'static`
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
* [*Route::h()*](../actix_web/struct.Route.html#method.h) registers a handler object
|
|
|
|
that implements the `Handler` trait. This is similar to `f()` method - only one handler can
|
2018-01-13 20:17:48 +01:00
|
|
|
be registered. Handler registration is the last config operation.
|
2017-12-20 07:36:06 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
* [*Route::a()*](../actix_web/struct.Route.html#method.a) registers an async handler
|
|
|
|
function for this route. Only one handler can be registered. Handler registration
|
|
|
|
is the last config operation. Handler function can be a function or closure and has the type
|
2017-12-20 07:36:06 +01:00
|
|
|
`Fn(HttpRequest<S>) -> Future<Item = HttpResponse, Error = Error> + 'static`
|
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
## Route matching
|
|
|
|
|
|
|
|
The main purpose of route configuration is to match (or not match) the request's `path`
|
|
|
|
against a URL path pattern. `path` represents the path portion of the URL that was requested.
|
|
|
|
|
|
|
|
The way that *actix* does this is very simple. When a request enters the system,
|
2018-02-22 07:00:22 +01:00
|
|
|
for each resource configuration declaration present in the system, actix checks
|
|
|
|
the request's path against the pattern declared. This checking happens in the order that
|
2018-03-28 22:16:01 +02:00
|
|
|
the routes were declared via `Application::resource()` method. If resource can not be found,
|
|
|
|
the *default resource* is used as the matched resource.
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
When a route configuration is declared, it may contain route predicate arguments. All route
|
2017-12-30 21:13:23 +01:00
|
|
|
predicates associated with a route declaration must be `true` for the route configuration to
|
2017-12-11 23:16:29 +01:00
|
|
|
be used for a given request during a check. If any predicate in the set of route predicate
|
|
|
|
arguments provided to a route configuration returns `false` during a check, that route is
|
|
|
|
skipped and route matching continues through the ordered set of routes.
|
|
|
|
|
|
|
|
If any route matches, the route matching process stops and the handler associated with
|
2018-03-28 22:16:01 +02:00
|
|
|
the route is invoked.
|
2017-12-11 23:16:29 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
If no route matches after all route patterns are exhausted, a *NOT FOUND* response get returned.
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
## Resource pattern syntax
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
The syntax of the pattern matching language used by actix in the pattern
|
2017-12-30 21:13:23 +01:00
|
|
|
argument is straightforward.
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
The pattern used in route configuration may start with a slash character. If the pattern
|
2017-12-30 21:13:23 +01:00
|
|
|
does not start with a slash character, an implicit slash will be prepended
|
2017-12-11 23:16:29 +01:00
|
|
|
to it at matching time. For example, the following patterns are equivalent:
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
```
|
|
|
|
{foo}/bar/baz
|
2017-12-02 08:42:21 +01:00
|
|
|
```
|
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
and:
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
```
|
|
|
|
/{foo}/bar/baz
|
|
|
|
```
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
A *variable part* (replacement marker) is specified in the form *{identifier}*,
|
|
|
|
where this means "accept any characters up to the next slash character and use this
|
|
|
|
as the name in the `HttpRequest.match_info()` object".
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
A replacement marker in a pattern matches the regular expression `[^{}/]+`.
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
A match_info is the `Params` object representing the dynamic parts extracted from a
|
2017-12-11 23:16:29 +01:00
|
|
|
*URL* based on the routing pattern. It is available as *request.match_info*. For example, the
|
|
|
|
following pattern defines one literal segment (foo) and two replacement markers (baz, and bar):
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
```
|
|
|
|
foo/{baz}/{bar}
|
|
|
|
```
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
The above pattern will match these URLs, generating the following match information:
|
|
|
|
|
|
|
|
```
|
|
|
|
foo/1/2 -> Params {'baz':'1', 'bar':'2'}
|
|
|
|
foo/abc/def -> Params {'baz':'abc', 'bar':'def'}
|
2017-12-02 08:42:21 +01:00
|
|
|
```
|
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
It will not match the following patterns however:
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
```
|
|
|
|
foo/1/2/ -> No match (trailing slash)
|
|
|
|
bar/abc/def -> First segment literal mismatch
|
|
|
|
```
|
2017-12-02 08:42:21 +01:00
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
The match for a segment replacement marker in a segment will be done only up to
|
|
|
|
the first non-alphanumeric character in the segment in the pattern. So, for instance,
|
2017-12-11 23:16:29 +01:00
|
|
|
if this route pattern was used:
|
|
|
|
|
|
|
|
```
|
|
|
|
foo/{name}.html
|
|
|
|
```
|
|
|
|
|
|
|
|
The literal path */foo/biz.html* will match the above route pattern, and the match result
|
2017-12-30 21:13:23 +01:00
|
|
|
will be `Params{'name': 'biz'}`. However, the literal path */foo/biz* will not match,
|
|
|
|
because it does not contain a literal *.html* at the end of the segment represented
|
2017-12-11 23:16:29 +01:00
|
|
|
by *{name}.html* (it only contains biz, not biz.html).
|
|
|
|
|
|
|
|
To capture both segments, two replacement markers can be used:
|
|
|
|
|
|
|
|
```
|
|
|
|
foo/{name}.{ext}
|
|
|
|
```
|
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
The literal path */foo/biz.html* will match the above route pattern, and the match
|
|
|
|
result will be *Params{'name': 'biz', 'ext': 'html'}*. This occurs because there is a
|
2017-12-11 23:16:29 +01:00
|
|
|
literal part of *.* (period) between the two replacement markers *{name}* and *{ext}*.
|
|
|
|
|
|
|
|
Replacement markers can optionally specify a regular expression which will be used to decide
|
|
|
|
whether a path segment should match the marker. To specify that a replacement marker should
|
|
|
|
match only a specific set of characters as defined by a regular expression, you must use a
|
|
|
|
slightly extended form of replacement marker syntax. Within braces, the replacement marker
|
2017-12-30 21:13:23 +01:00
|
|
|
name must be followed by a colon, then directly thereafter, the regular expression. The default
|
2017-12-11 23:16:29 +01:00
|
|
|
regular expression associated with a replacement marker *[^/]+* matches one or more characters
|
|
|
|
which are not a slash. For example, under the hood, the replacement marker *{foo}* can more
|
|
|
|
verbosely be spelled as *{foo:[^/]+}*. You can change this to be an arbitrary regular expression
|
|
|
|
to match an arbitrary sequence of characters, such as *{foo:\d+}* to match only digits.
|
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
Segments must contain at least one character in order to match a segment replacement marker.
|
2017-12-11 23:16:29 +01:00
|
|
|
For example, for the URL */abc/*:
|
|
|
|
|
|
|
|
* */abc/{foo}* will not match.
|
|
|
|
* */{foo}/* will match.
|
|
|
|
|
|
|
|
Note that path will be URL-unquoted and decoded into valid unicode string before
|
|
|
|
matching pattern and values representing matched path segments will be URL-unquoted too.
|
|
|
|
So for instance, the following pattern:
|
|
|
|
|
|
|
|
```
|
|
|
|
foo/{bar}
|
|
|
|
```
|
|
|
|
|
|
|
|
When matching the following URL:
|
|
|
|
|
|
|
|
```
|
|
|
|
http://example.com/foo/La%20Pe%C3%B1a
|
|
|
|
```
|
|
|
|
|
|
|
|
The matchdict will look like so (the value is URL-decoded):
|
|
|
|
|
|
|
|
```
|
|
|
|
Params{'bar': 'La Pe\xf1a'}
|
|
|
|
```
|
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
Literal strings in the path segment should represent the decoded value of the
|
2017-12-11 23:16:29 +01:00
|
|
|
path provided to actix. You don't want to use a URL-encoded value in the pattern.
|
|
|
|
For example, rather than this:
|
|
|
|
|
|
|
|
```
|
|
|
|
/Foo%20Bar/{baz}
|
|
|
|
```
|
|
|
|
|
|
|
|
You'll want to use something like this:
|
|
|
|
|
|
|
|
```
|
|
|
|
/Foo Bar/{baz}
|
|
|
|
```
|
|
|
|
|
|
|
|
It is possible to get "tail match". For this purpose custom regex has to be used.
|
|
|
|
|
|
|
|
```
|
|
|
|
foo/{bar}/{tail:.*}
|
2017-12-02 08:42:21 +01:00
|
|
|
```
|
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
The above pattern will match these URLs, generating the following match information:
|
|
|
|
|
|
|
|
```
|
|
|
|
foo/1/2/ -> Params{'bar':'1', 'tail': '2/'}
|
|
|
|
foo/abc/def/a/b/c -> Params{'bar':u'abc', 'tail': 'def/a/b/c'}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Match information
|
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
All values representing matched path segments are available in
|
2017-12-11 23:16:29 +01:00
|
|
|
[`HttpRequest::match_info`](../actix_web/struct.HttpRequest.html#method.match_info).
|
2018-03-28 22:16:01 +02:00
|
|
|
Specific values can be retrieved with
|
|
|
|
[`Params::get()`](../actix_web/dev/struct.Params.html#method.get).
|
2017-12-11 23:16:29 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
Any matched parameter can be deserialized into a specific type if the type
|
|
|
|
implements the `FromParam` trait. For example most standard integer types
|
|
|
|
the trait, i.e.:
|
2017-12-02 19:17:15 +01:00
|
|
|
|
|
|
|
```rust
|
2017-12-05 05:38:38 +01:00
|
|
|
# extern crate actix_web;
|
2017-12-02 19:17:15 +01:00
|
|
|
use actix_web::*;
|
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
fn index(req: HttpRequest) -> Result<String> {
|
2017-12-02 19:17:15 +01:00
|
|
|
let v1: u8 = req.match_info().query("v1")?;
|
|
|
|
let v2: u8 = req.match_info().query("v2")?;
|
2017-12-03 23:22:04 +01:00
|
|
|
Ok(format!("Values {} {}", v1, v2))
|
2017-12-02 19:17:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
Application::new()
|
2017-12-06 17:03:08 +01:00
|
|
|
.resource(r"/a/{v1}/{v2}/", |r| r.f(index))
|
2017-12-02 19:17:15 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
For this example for path '/a/1/2/', values v1 and v2 will resolve to "1" and "2".
|
|
|
|
|
|
|
|
It is possible to create a `PathBuf` from a tail path parameter. The returned `PathBuf` is
|
|
|
|
percent-decoded. If a segment is equal to "..", the previous segment (if
|
|
|
|
any) is skipped.
|
|
|
|
|
|
|
|
For security purposes, if a segment meets any of the following conditions,
|
|
|
|
an `Err` is returned indicating the condition met:
|
|
|
|
|
|
|
|
* Decoded segment starts with any of: `.` (except `..`), `*`
|
|
|
|
* Decoded segment ends with any of: `:`, `>`, `<`
|
|
|
|
* Decoded segment contains any of: `/`
|
|
|
|
* On Windows, decoded segment contains any of: '\'
|
|
|
|
* Percent-encoding results in invalid UTF8.
|
|
|
|
|
|
|
|
As a result of these conditions, a `PathBuf` parsed from request path parameter is
|
2017-12-04 22:32:05 +01:00
|
|
|
safe to interpolate within, or use as a suffix of, a path without additional checks.
|
2017-12-02 19:17:15 +01:00
|
|
|
|
|
|
|
```rust
|
2017-12-04 22:32:05 +01:00
|
|
|
# extern crate actix_web;
|
2017-12-02 19:17:15 +01:00
|
|
|
use std::path::PathBuf;
|
2018-03-31 02:31:18 +02:00
|
|
|
use actix_web::{Application, HttpRequest, Result, http::Method};
|
2017-12-02 19:17:15 +01:00
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
fn index(req: HttpRequest) -> Result<String> {
|
2017-12-02 19:17:15 +01:00
|
|
|
let path: PathBuf = req.match_info().query("tail")?;
|
2017-12-03 23:22:04 +01:00
|
|
|
Ok(format!("Path {:?}", path))
|
2017-12-02 19:17:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
Application::new()
|
2017-12-04 23:07:53 +01:00
|
|
|
.resource(r"/a/{tail:.*}", |r| r.method(Method::GET).f(index))
|
2017-12-02 19:17:15 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
2017-12-09 22:58:24 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
List of `FromParam` implementations can be found in
|
2017-12-11 23:16:29 +01:00
|
|
|
[api docs](../actix_web/dev/trait.FromParam.html#foreign-impls)
|
|
|
|
|
2018-03-27 03:35:08 +02:00
|
|
|
## Path information extractor
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
Actix provides functionality for type safe request path information extraction.
|
2018-03-27 03:35:08 +02:00
|
|
|
It uses *serde* package as a deserialization library.
|
2018-03-29 19:01:07 +02:00
|
|
|
[Path](../actix_web/struct.Path.html) extracts information, the destination type
|
|
|
|
has to implement *serde's *`Deserialize` trait.
|
2018-03-27 03:35:08 +02:00
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate bytes;
|
|
|
|
# extern crate actix_web;
|
|
|
|
# extern crate futures;
|
|
|
|
#[macro_use] extern crate serde_derive;
|
2018-03-31 02:31:18 +02:00
|
|
|
use actix_web::{Application, Path, Result, http::Method};
|
2018-03-27 03:35:08 +02:00
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Info {
|
|
|
|
username: String,
|
|
|
|
}
|
|
|
|
|
2018-03-29 19:01:07 +02:00
|
|
|
// extract path info using serde
|
|
|
|
fn index(info: Path<Info>) -> Result<String> {
|
2018-03-27 03:35:08 +02:00
|
|
|
Ok(format!("Welcome {}!", info.username))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let app = Application::new()
|
|
|
|
.resource("/{username}/index.html", // <- define path parameters
|
2018-03-29 19:01:07 +02:00
|
|
|
|r| r.method(Method::GET).with(index));
|
2018-03-27 03:35:08 +02:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-03-29 19:01:07 +02:00
|
|
|
[Query](../actix_web/struct.Query.html) provides similar functionality for
|
|
|
|
request query parameters.
|
2018-03-27 03:35:08 +02:00
|
|
|
|
|
|
|
|
2017-12-11 23:16:29 +01:00
|
|
|
## Generating resource URLs
|
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
Use the [HttpRequest.url_for()](../actix_web/struct.HttpRequest.html#method.url_for)
|
|
|
|
method to generate URLs based on resource patterns. For example, if you've configured a
|
2018-03-28 22:16:01 +02:00
|
|
|
resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this:
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
2018-03-31 02:31:18 +02:00
|
|
|
# use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
|
2017-12-30 21:13:23 +01:00
|
|
|
#
|
2017-12-11 23:16:29 +01:00
|
|
|
fn index(req: HttpRequest) -> HttpResponse {
|
2017-12-19 20:34:51 +01:00
|
|
|
let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
|
2018-03-31 08:07:33 +02:00
|
|
|
HttpResponse::Ok().into()
|
2017-12-19 20:34:51 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let app = Application::new()
|
2017-12-20 07:36:06 +01:00
|
|
|
.resource("/test/{a}/{b}/{c}", |r| {
|
2017-12-19 20:34:51 +01:00
|
|
|
r.name("foo"); // <- set resource name, then it could be used in `url_for`
|
2018-03-31 08:07:33 +02:00
|
|
|
r.method(Method::GET).f(|_| HttpResponse::Ok());
|
2017-12-19 20:34:51 +01:00
|
|
|
})
|
|
|
|
.finish();
|
2017-12-11 23:16:29 +01:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2017-12-20 07:36:06 +01:00
|
|
|
This would return something like the string *http://example.com/test/1/2/3* (at least if
|
2017-12-11 23:16:29 +01:00
|
|
|
the current protocol and hostname implied http://example.com).
|
2018-03-28 22:16:01 +02:00
|
|
|
`url_for()` method returns [*Url object*](https://docs.rs/url/1.6.0/url/struct.Url.html) so you
|
2017-12-11 23:16:29 +01:00
|
|
|
can modify this url (add query parameters, anchor, etc).
|
|
|
|
`url_for()` could be called only for *named* resources otherwise error get returned.
|
|
|
|
|
|
|
|
## External resources
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
Resources that are valid URLs, can be registered as external resources. They are useful
|
2017-12-11 23:16:29 +01:00
|
|
|
for URL generation purposes only and are never considered for matching at request time.
|
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
2018-03-31 08:07:33 +02:00
|
|
|
use actix_web::{Application, HttpRequest, HttpResponse, Error};
|
2017-12-11 23:16:29 +01:00
|
|
|
|
2018-03-31 08:07:33 +02:00
|
|
|
fn index(mut req: HttpRequest) -> Result<HttpResponse, Error> {
|
2017-12-11 23:16:29 +01:00
|
|
|
let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
|
|
|
|
assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
|
2018-03-31 08:07:33 +02:00
|
|
|
Ok(HttpResponse::Ok().into())
|
2017-12-11 23:16:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let app = Application::new()
|
|
|
|
.resource("/index.html", |r| r.f(index))
|
|
|
|
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
|
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## Path normalization and redirecting to slash-appended routes
|
2017-12-09 22:58:24 +01:00
|
|
|
|
|
|
|
By normalizing it means:
|
|
|
|
|
|
|
|
- Add a trailing slash to the path.
|
|
|
|
- Double slashes are replaced by one.
|
|
|
|
|
|
|
|
The handler returns as soon as it finds a path that resolves
|
|
|
|
correctly. The order if all enable is 1) merge, 3) both merge and append
|
|
|
|
and 3) append. If the path resolves with
|
|
|
|
at least one of those conditions, it will redirect to the new path.
|
|
|
|
|
|
|
|
If *append* is *true* append slash when needed. If a resource is
|
2018-03-28 22:16:01 +02:00
|
|
|
defined with trailing slash and the request doesn't have one, it will
|
|
|
|
be appended automatically.
|
2017-12-09 22:58:24 +01:00
|
|
|
|
|
|
|
If *merge* is *true*, merge multiple consecutive slashes in the path into one.
|
|
|
|
|
|
|
|
This handler designed to be use as a handler for application's *default resource*.
|
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
|
|
|
# #[macro_use] extern crate serde_derive;
|
|
|
|
# use actix_web::*;
|
2018-03-31 02:31:18 +02:00
|
|
|
use actix_web::http::NormalizePath;
|
2017-12-09 22:58:24 +01:00
|
|
|
#
|
2018-03-31 08:07:33 +02:00
|
|
|
# fn index(req: HttpRequest) -> HttpResponse {
|
|
|
|
# HttpResponse::Ok().into()
|
2017-12-09 22:58:24 +01:00
|
|
|
# }
|
|
|
|
fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
let app = Application::new()
|
2017-12-09 22:58:24 +01:00
|
|
|
.resource("/resource/", |r| r.f(index))
|
|
|
|
.default_resource(|r| r.h(NormalizePath::default()))
|
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
In this example `/resource`, `//resource///` will be redirected to `/resource/`.
|
2017-12-09 23:06:22 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
In this example path normalization handler is registered for all methods,
|
2017-12-09 23:06:22 +01:00
|
|
|
but you should not rely on this mechanism to redirect *POST* requests. The redirect of the
|
2017-12-30 21:13:23 +01:00
|
|
|
slash-appending *Not Found* will turn a *POST* request into a GET, losing any
|
2017-12-09 23:06:22 +01:00
|
|
|
*POST* data in the original request.
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
It is possible to register path normalization only for *GET* requests only:
|
2017-12-09 23:06:22 +01:00
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
|
|
|
# #[macro_use] extern crate serde_derive;
|
2018-03-31 08:07:33 +02:00
|
|
|
use actix_web::{Application, HttpRequest, http::Method, http::NormalizePath};
|
2017-12-09 23:06:22 +01:00
|
|
|
#
|
2018-03-31 08:07:33 +02:00
|
|
|
# fn index(req: HttpRequest) -> &'static str {
|
|
|
|
# "test"
|
2017-12-09 23:06:22 +01:00
|
|
|
# }
|
|
|
|
fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
let app = Application::new()
|
2017-12-09 23:06:22 +01:00
|
|
|
.resource("/resource/", |r| r.f(index))
|
|
|
|
.default_resource(|r| r.method(Method::GET).h(NormalizePath::default()))
|
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
2017-12-11 23:16:29 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
## Using an Application Prefix to Compose Applications
|
2017-12-11 23:16:29 +01:00
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
The `Application::prefix()`" method allows to set a specific application prefix.
|
2017-12-30 21:13:23 +01:00
|
|
|
This prefix represents a resource prefix that will be prepended to all resource patterns added
|
2017-12-11 23:16:29 +01:00
|
|
|
by the resource configuration. This can be used to help mount a set of routes at a different
|
|
|
|
location than the included callable's author intended while still maintaining the same
|
2017-12-30 21:13:23 +01:00
|
|
|
resource names.
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
|
|
|
# use actix_web::*;
|
2017-12-30 21:13:23 +01:00
|
|
|
#
|
2017-12-11 23:16:29 +01:00
|
|
|
fn show_users(req: HttpRequest) -> HttpResponse {
|
|
|
|
unimplemented!()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
Application::new()
|
|
|
|
.prefix("/users")
|
|
|
|
.resource("/show", |r| r.f(show_users))
|
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2017-12-30 21:13:23 +01:00
|
|
|
In the above example, the *show_users* route will have an effective route pattern of
|
|
|
|
*/users/show* instead of */show* because the application's prefix argument will be prepended
|
2017-12-29 23:04:13 +01:00
|
|
|
to the pattern. The route will then only match if the URL path is */users/show*,
|
2017-12-30 21:13:23 +01:00
|
|
|
and when the `HttpRequest.url_for()` function is called with the route name show_users,
|
2017-12-11 23:16:29 +01:00
|
|
|
it will generate a URL with that same path.
|
|
|
|
|
|
|
|
## Custom route predicates
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
You can think of a predicate as a simple function that accepts a *request* object reference
|
|
|
|
and returns *true* or *false*. Formally, a predicate is any object that implements the
|
2017-12-11 23:16:29 +01:00
|
|
|
[`Predicate`](../actix_web/pred/trait.Predicate.html) trait. Actix provides
|
2017-12-30 21:13:23 +01:00
|
|
|
several predicates, you can check [functions section](../actix_web/pred/index.html#functions)
|
2017-12-11 23:16:29 +01:00
|
|
|
of api docs.
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
Here is a simple predicate that check that a request contains a specific *header*:
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
|
|
|
# use actix_web::*;
|
2018-03-31 08:07:33 +02:00
|
|
|
use actix_web::{http, pred::Predicate, Application, HttpRequest};
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
struct ContentTypeHeader;
|
|
|
|
|
|
|
|
impl<S: 'static> Predicate<S> for ContentTypeHeader {
|
|
|
|
|
|
|
|
fn check(&self, req: &mut HttpRequest<S>) -> bool {
|
2018-03-31 08:07:33 +02:00
|
|
|
req.headers().contains_key(http::header::CONTENT_TYPE)
|
2017-12-11 23:16:29 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
Application::new()
|
|
|
|
.resource("/index.html", |r|
|
|
|
|
r.route()
|
2018-03-02 03:32:31 +01:00
|
|
|
.filter(ContentTypeHeader)
|
2018-03-31 08:07:33 +02:00
|
|
|
.f(|_| HttpResponse::Ok()));
|
2017-12-11 23:16:29 +01:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
In this example *index* handler will be called only if request contains *CONTENT-TYPE* header.
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
Predicates have access to the application's state via `HttpRequest::state()`.
|
2017-12-11 23:16:29 +01:00
|
|
|
Also predicates can store extra information in
|
2018-03-28 22:16:01 +02:00
|
|
|
[request extensions](../actix_web/struct.HttpRequest.html#method.extensions).
|
2017-12-11 23:16:29 +01:00
|
|
|
|
2018-01-13 20:17:48 +01:00
|
|
|
### Modifying predicate values
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
You can invert the meaning of any predicate value by wrapping it in a `Not` predicate.
|
|
|
|
For example if you want to return "METHOD NOT ALLOWED" response for all methods
|
|
|
|
except "GET":
|
|
|
|
|
|
|
|
```rust
|
|
|
|
# extern crate actix_web;
|
|
|
|
# extern crate http;
|
|
|
|
# use actix_web::*;
|
2018-03-31 08:07:33 +02:00
|
|
|
use actix_web::{pred, Application, HttpResponse};
|
2017-12-11 23:16:29 +01:00
|
|
|
|
|
|
|
fn main() {
|
|
|
|
Application::new()
|
|
|
|
.resource("/index.html", |r|
|
|
|
|
r.route()
|
2018-03-02 03:32:31 +01:00
|
|
|
.filter(pred::Not(pred::Get()))
|
2018-03-31 08:07:33 +02:00
|
|
|
.f(|req| HttpResponse::MethodNotAllowed()))
|
2017-12-11 23:16:29 +01:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
The `Any` predicate accepts a list of predicates and matches if any of the supplied
|
2017-12-11 23:16:29 +01:00
|
|
|
predicates match. i.e:
|
|
|
|
|
|
|
|
```rust,ignore
|
2017-12-20 22:23:50 +01:00
|
|
|
pred::Any(pred::Get()).or(pred::Post())
|
2017-12-11 23:16:29 +01:00
|
|
|
```
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
The `All` predicate accepts a list of predicates and matches if all of the supplied
|
2017-12-11 23:16:29 +01:00
|
|
|
predicates match. i.e:
|
|
|
|
|
|
|
|
```rust,ignore
|
2017-12-20 22:23:50 +01:00
|
|
|
pred::All(pred::Get()).and(pred::Header("content-type", "plain/text"))
|
2017-12-11 23:16:29 +01:00
|
|
|
```
|
2017-12-12 01:26:51 +01:00
|
|
|
|
|
|
|
## Changing the default Not Found response
|
|
|
|
|
2018-03-28 22:16:01 +02:00
|
|
|
If the path pattern can not be found in the routing table or a resource can not find matching
|
|
|
|
route, the default resource is used. The default response is *NOT FOUND*.
|
|
|
|
It is possible to override the *NOT FOUND* response with `Application::default_resource()`.
|
|
|
|
This method accepts a *configuration function* same as normal resource configuration
|
2017-12-12 01:26:51 +01:00
|
|
|
with `Application::resource()` method.
|
|
|
|
|
2017-12-12 01:50:51 +01:00
|
|
|
```rust
|
2017-12-12 01:26:51 +01:00
|
|
|
# extern crate actix_web;
|
2018-03-31 08:07:33 +02:00
|
|
|
use actix_web::{Application, HttpResponse, http::Method, pred};
|
2017-12-12 01:26:51 +01:00
|
|
|
|
|
|
|
fn main() {
|
|
|
|
Application::new()
|
2017-12-12 04:16:45 +01:00
|
|
|
.default_resource(|r| {
|
2018-03-31 08:07:33 +02:00
|
|
|
r.method(Method::GET).f(|req| HttpResponse::NotFound());
|
|
|
|
r.route().filter(pred::Not(pred::Get()))
|
|
|
|
.f(|req| HttpResponse::MethodNotAllowed());
|
2017-12-12 01:26:51 +01:00
|
|
|
})
|
2017-12-20 07:36:06 +01:00
|
|
|
# .finish();
|
2017-12-12 01:26:51 +01:00
|
|
|
}
|
|
|
|
```
|