1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-28 10:02:38 +01:00
actix-web/src/router.rs

176 lines
5.1 KiB
Rust
Raw Normal View History

2017-10-07 06:48:14 +02:00
use std::rc::Rc;
use std::string::ToString;
use std::collections::HashMap;
use task::Task;
2017-10-09 05:16:48 +02:00
use payload::Payload;
use route::RouteHandler;
2017-10-08 23:56:51 +02:00
use resource::Resource;
2017-10-17 04:21:24 +02:00
use recognizer::{RouteRecognizer, check_pattern};
2017-10-08 23:56:51 +02:00
use application::Application;
2017-10-07 06:48:14 +02:00
use httpcodes::HTTPNotFound;
use httprequest::HttpRequest;
2017-10-07 06:48:14 +02:00
2017-10-08 23:56:51 +02:00
pub(crate) trait Handler: 'static {
2017-10-09 05:16:48 +02:00
fn handle(&self, req: HttpRequest, payload: Payload) -> Task;
2017-10-07 06:48:14 +02:00
}
2017-10-15 23:17:41 +02:00
/// Server routing map
pub struct Router {
apps: HashMap<String, Box<Handler>>,
2017-10-17 04:21:24 +02:00
resources: RouteRecognizer<Resource>,
2017-10-15 23:17:41 +02:00
}
impl Router {
pub(crate) fn call(&self, req: HttpRequest, payload: Payload) -> Task
{
2017-10-17 04:21:24 +02:00
if let Some((params, h)) = self.resources.recognize(req.path()) {
if let Some(params) = params {
h.handle(
req.with_match_info(params), payload, Rc::new(()))
} else {
h.handle(req, payload, Rc::new(()))
}
2017-10-15 23:17:41 +02:00
} else {
for (prefix, app) in &self.apps {
if req.path().starts_with(prefix) {
return app.handle(req, payload)
}
}
Task::reply(HTTPNotFound.response())
}
}
}
/// Request routing map builder
2017-10-08 08:59:57 +02:00
///
2017-10-17 04:21:24 +02:00
/// Resource may have variable path also. For instance, a resource with
/// the path '/a/{name}/c' would match all incoming requests with paths
/// such as '/a/b/c', '/a/1/c', and '/a/etc/c'.
///
/// 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.
///
/// By default, each part matches the regular expression [^{}/]+.
2017-10-08 08:59:57 +02:00
///
2017-10-17 04:21:24 +02:00
/// You can also specify a custom regex in the form {identifier:regex}:
///
/// For instance, to route Get requests on any route matching /users/{userid}/{friend} and
2017-10-08 08:59:57 +02:00
/// store userid and friend in the exposed Params object:
///
/// ```rust,ignore
2017-10-15 23:17:41 +02:00
/// let mut map = RoutingMap::default();
2017-10-08 08:59:57 +02:00
///
2017-10-17 04:21:24 +02:00
/// map.resource("/users/{userid}/{friend}", |r| r.get::<MyRoute>());
2017-10-08 08:59:57 +02:00
/// ```
2017-10-07 06:48:14 +02:00
pub struct RoutingMap {
2017-10-15 23:17:41 +02:00
parts: Option<RoutingMapParts>,
}
struct RoutingMapParts {
2017-10-08 23:56:51 +02:00
apps: HashMap<String, Box<Handler>>,
resources: HashMap<String, Resource>,
2017-10-07 06:48:14 +02:00
}
impl Default for RoutingMap {
fn default() -> Self {
RoutingMap {
2017-10-15 23:17:41 +02:00
parts: Some(RoutingMapParts {
apps: HashMap::new(),
resources: HashMap::new()}),
2017-10-07 06:48:14 +02:00
}
}
}
impl RoutingMap {
2017-10-08 23:56:51 +02:00
/// Add `Application` object with specific prefix.
2017-10-08 08:59:57 +02:00
/// Application prefixes all registered resources with specified prefix.
///
/// ```rust,ignore
///
/// struct MyRoute;
///
/// fn main() {
2017-10-15 23:17:41 +02:00
/// let mut router =
/// RoutingMap::default()
/// .app("/pre", Application::default()
/// .resource("/test", |r| {
/// r.get::<MyRoute>();
/// r.post::<MyRoute>();
/// })
/// .finish()
/// ).finish();
2017-10-08 08:59:57 +02:00
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../pre/test` url.
2017-10-15 23:17:41 +02:00
pub fn app<P, S: 'static>(&mut self, prefix: P, app: Application<S>) -> &mut Self
2017-10-07 06:48:14 +02:00
where P: ToString
{
2017-10-15 23:17:41 +02:00
{
let parts = self.parts.as_mut().expect("Use after finish");
2017-10-07 06:48:14 +02:00
2017-10-15 23:17:41 +02:00
// we can not override registered resource
let prefix = prefix.to_string();
if parts.apps.contains_key(&prefix) {
panic!("Resource is registered: {}", prefix);
}
2017-10-07 06:48:14 +02:00
2017-10-15 23:17:41 +02:00
// add application
parts.apps.insert(prefix.clone(), app.prepare(prefix));
}
self
2017-10-07 06:48:14 +02:00
}
2017-10-15 23:17:41 +02:00
/// Configure resource for specific path.
2017-10-08 08:59:57 +02:00
///
/// ```rust,ignore
///
/// struct MyRoute;
///
/// fn main() {
2017-10-15 23:17:41 +02:00
/// RoutingMap::default().resource("/test", |r| {
/// r.post::<MyRoute>();
/// }).finish();
2017-10-08 08:59:57 +02:00
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../test` url.
2017-10-15 23:17:41 +02:00
pub fn resource<P, F>(&mut self, path: P, f: F) -> &mut Self
where F: FnOnce(&mut Resource<()>) + 'static,
P: ToString,
2017-10-07 06:48:14 +02:00
{
2017-10-15 23:17:41 +02:00
{
let parts = self.parts.as_mut().expect("Use after finish");
2017-10-07 06:48:14 +02:00
2017-10-15 23:17:41 +02:00
// add resource
let path = path.to_string();
if !parts.resources.contains_key(&path) {
2017-10-17 04:21:24 +02:00
check_pattern(&path);
2017-10-15 23:17:41 +02:00
parts.resources.insert(path.clone(), Resource::default());
}
// configure resource
f(parts.resources.get_mut(&path).unwrap());
2017-10-07 06:48:14 +02:00
}
2017-10-15 23:17:41 +02:00
self
2017-10-07 06:48:14 +02:00
}
2017-10-15 23:17:41 +02:00
/// Finish configuration and create `Router` instance
pub fn finish(&mut self) -> Router
{
let parts = self.parts.take().expect("Use after finish");
2017-10-17 04:21:24 +02:00
let mut routes = Vec::new();
2017-10-15 23:17:41 +02:00
for (path, resource) in parts.resources {
2017-10-17 04:21:24 +02:00
routes.push((path, resource))
2017-10-07 06:48:14 +02:00
}
Router {
2017-10-15 23:17:41 +02:00
apps: parts.apps,
2017-10-17 04:21:24 +02:00
resources: RouteRecognizer::new("/".to_owned(), routes),
2017-10-07 06:48:14 +02:00
}
}
}