1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-10-11 04:32:28 +00:00
actix-web/src/router.rs

162 lines
4.5 KiB
Rust
Raw Normal View History

2017-10-07 04:48:14 +00:00
use std::rc::Rc;
use std::string::ToString;
use std::collections::HashMap;
use route_recognizer::{Router as Recognizer};
use task::Task;
2017-10-09 03:16:48 +00:00
use payload::Payload;
use route::RouteHandler;
2017-10-08 21:56:51 +00:00
use resource::Resource;
use application::Application;
2017-10-07 04:48:14 +00:00
use httpcodes::HTTPNotFound;
use httprequest::HttpRequest;
2017-10-07 04:48:14 +00:00
2017-10-08 21:56:51 +00:00
pub(crate) trait Handler: 'static {
2017-10-09 03:16:48 +00:00
fn handle(&self, req: HttpRequest, payload: Payload) -> Task;
2017-10-07 04:48:14 +00:00
}
2017-10-15 21:17:41 +00:00
/// Server routing map
pub struct Router {
apps: HashMap<String, Box<Handler>>,
resources: Recognizer<Resource>,
}
impl Router {
pub(crate) fn call(&self, req: HttpRequest, payload: Payload) -> Task
{
if let Ok(h) = self.resources.recognize(req.path()) {
h.handler.handle(req.with_params(h.params), payload, Rc::new(()))
} 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 06:59:57 +00:00
///
/// Route supports glob patterns: * for a single wildcard segment and :param
/// for matching storing that segment of the request url in the Params object,
/// which is stored in the request.
///
/// For instance, to route Get requests on any route matching /users/:userid/:friend and
/// store userid and friend in the exposed Params object:
///
/// ```rust,ignore
2017-10-15 21:17:41 +00:00
/// let mut map = RoutingMap::default();
2017-10-08 06:59:57 +00:00
///
2017-10-15 21:17:41 +00:00
/// map.resource("/users/:userid/:friendid", |r| r.get::<MyRoute>());
2017-10-08 06:59:57 +00:00
/// ```
2017-10-07 04:48:14 +00:00
pub struct RoutingMap {
2017-10-15 21:17:41 +00:00
parts: Option<RoutingMapParts>,
}
struct RoutingMapParts {
2017-10-08 21:56:51 +00:00
apps: HashMap<String, Box<Handler>>,
resources: HashMap<String, Resource>,
2017-10-07 04:48:14 +00:00
}
impl Default for RoutingMap {
fn default() -> Self {
RoutingMap {
2017-10-15 21:17:41 +00:00
parts: Some(RoutingMapParts {
apps: HashMap::new(),
resources: HashMap::new()}),
2017-10-07 04:48:14 +00:00
}
}
}
impl RoutingMap {
2017-10-08 21:56:51 +00:00
/// Add `Application` object with specific prefix.
2017-10-08 06:59:57 +00:00
/// Application prefixes all registered resources with specified prefix.
///
/// ```rust,ignore
///
/// struct MyRoute;
///
/// fn main() {
2017-10-15 21:17:41 +00:00
/// let mut router =
/// RoutingMap::default()
/// .app("/pre", Application::default()
/// .resource("/test", |r| {
/// r.get::<MyRoute>();
/// r.post::<MyRoute>();
/// })
/// .finish()
/// ).finish();
2017-10-08 06:59:57 +00:00
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../pre/test` url.
2017-10-15 21:17:41 +00:00
pub fn app<P, S: 'static>(&mut self, prefix: P, app: Application<S>) -> &mut Self
2017-10-07 04:48:14 +00:00
where P: ToString
{
2017-10-15 21:17:41 +00:00
{
let parts = self.parts.as_mut().expect("Use after finish");
2017-10-07 04:48:14 +00:00
2017-10-15 21:17:41 +00: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 04:48:14 +00:00
2017-10-15 21:17:41 +00:00
// add application
parts.apps.insert(prefix.clone(), app.prepare(prefix));
}
self
2017-10-07 04:48:14 +00:00
}
2017-10-15 21:17:41 +00:00
/// Configure resource for specific path.
2017-10-08 06:59:57 +00:00
///
/// ```rust,ignore
///
/// struct MyRoute;
///
/// fn main() {
2017-10-15 21:17:41 +00:00
/// RoutingMap::default().resource("/test", |r| {
/// r.post::<MyRoute>();
/// }).finish();
2017-10-08 06:59:57 +00:00
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../test` url.
2017-10-15 21:17:41 +00: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 04:48:14 +00:00
{
2017-10-15 21:17:41 +00:00
{
let parts = self.parts.as_mut().expect("Use after finish");
2017-10-07 04:48:14 +00:00
2017-10-15 21:17:41 +00:00
// add resource
let path = path.to_string();
if !parts.resources.contains_key(&path) {
parts.resources.insert(path.clone(), Resource::default());
}
// configure resource
f(parts.resources.get_mut(&path).unwrap());
2017-10-07 04:48:14 +00:00
}
2017-10-15 21:17:41 +00:00
self
2017-10-07 04:48:14 +00:00
}
2017-10-15 21:17:41 +00:00
/// Finish configuration and create `Router` instance
pub fn finish(&mut self) -> Router
{
let parts = self.parts.take().expect("Use after finish");
2017-10-07 04:48:14 +00:00
let mut router = Recognizer::new();
2017-10-15 21:17:41 +00:00
for (path, resource) in parts.resources {
2017-10-07 04:48:14 +00:00
router.add(path.as_str(), resource);
}
Router {
2017-10-15 21:17:41 +00:00
apps: parts.apps,
2017-10-07 04:48:14 +00:00
resources: router,
}
}
}