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/application.rs

264 lines
8.1 KiB
Rust
Raw Normal View History

2017-10-07 04:48:14 +00:00
use std::rc::Rc;
use std::collections::HashMap;
2017-12-05 21:31:06 +00:00
use error::UriGenerationError;
2017-12-04 22:53:40 +00:00
use handler::{Reply, RouteHandler};
2017-12-05 00:09:22 +00:00
use route::Route;
use resource::Resource;
2017-12-05 21:31:06 +00:00
use recognizer::{RouteRecognizer, check_pattern, PatternElement};
use httprequest::HttpRequest;
use channel::HttpHandler;
2017-11-25 06:15:52 +00:00
use pipeline::Pipeline;
2017-11-10 06:08:54 +00:00
use middlewares::Middleware;
2017-10-07 04:48:14 +00:00
2017-12-05 19:31:35 +00:00
pub struct Router<S>(Rc<RouteRecognizer<Resource<S>>>);
impl<S: 'static> Router<S> {
pub fn new(prefix: String, map: HashMap<String, Resource<S>>) -> Router<S>
{
let mut resources = Vec::new();
for (path, resource) in map {
resources.push((path, resource.get_name(), resource))
}
Router(Rc::new(RouteRecognizer::new(prefix, resources)))
}
2017-12-05 21:31:06 +00:00
pub fn has_route(&self, path: &str) -> bool {
self.0.recognize(path).is_some()
}
pub fn resource_path<'a, U>(&self, prefix: &str, name: &str, elements: U)
-> Result<String, UriGenerationError>
where U: IntoIterator<Item=&'a str>
{
if let Some(pattern) = self.0.get_pattern(name) {
let mut iter = elements.into_iter();
let mut vec = vec![prefix];
for el in pattern.elements() {
match *el {
PatternElement::Str(ref s) => vec.push(s),
PatternElement::Var(_) => {
if let Some(val) = iter.next() {
vec.push(val)
} else {
return Err(UriGenerationError::NotEnoughElements)
}
}
}
}
let s = vec.join("/").to_owned();
Ok(s)
} else {
Err(UriGenerationError::ResourceNotFound)
}
}
2017-12-05 19:31:35 +00:00
}
2017-10-07 04:48:14 +00:00
/// Application
2017-10-22 01:54:24 +00:00
pub struct Application<S> {
state: Rc<S>,
prefix: String,
2017-10-08 21:56:51 +00:00
default: Resource<S>,
2017-12-04 22:53:40 +00:00
routes: Vec<(String, Route<S>)>,
2017-12-05 19:31:35 +00:00
router: Router<S>,
middlewares: Rc<Vec<Box<Middleware>>>,
2017-10-07 04:48:14 +00:00
}
impl<S: 'static> Application<S> {
2017-10-07 04:48:14 +00:00
2017-11-30 23:13:56 +00:00
fn run(&self, req: HttpRequest) -> Reply {
2017-11-27 05:18:38 +00:00
let mut req = req.with_state(Rc::clone(&self.state));
2017-12-05 19:31:35 +00:00
if let Some((params, h)) = self.router.0.recognize(req.path()) {
2017-10-22 01:54:24 +00:00
if let Some(params) = params {
req.set_match_info(params);
2017-10-22 01:54:24 +00:00
}
2017-11-30 23:13:56 +00:00
h.handle(req)
2017-10-22 01:54:24 +00:00
} else {
2017-12-04 22:53:40 +00:00
for route in &self.routes {
if req.path().starts_with(&route.0) && route.1.check(&mut req) {
req.set_prefix(route.0.len());
return route.1.handle(req)
2017-10-22 01:54:24 +00:00
}
}
2017-11-30 23:13:56 +00:00
self.default.handle(req)
2017-10-10 06:07:32 +00:00
}
2017-10-07 04:48:14 +00:00
}
}
impl<S: 'static> HttpHandler for Application<S> {
2017-11-29 21:53:52 +00:00
fn handle(&self, req: HttpRequest) -> Result<Pipeline, HttpRequest> {
if req.path().starts_with(&self.prefix) {
Ok(Pipeline::new(req, Rc::clone(&self.middlewares),
2017-11-30 23:13:56 +00:00
&|req: HttpRequest| self.run(req)))
2017-11-29 21:53:52 +00:00
} else {
Err(req)
}
}
}
2017-10-15 21:17:41 +00:00
impl Application<()> {
/// Create default `ApplicationBuilder` with no state
2017-11-27 01:30:35 +00:00
pub fn default<T: Into<String>>(prefix: T) -> ApplicationBuilder<()> {
2017-10-15 21:17:41 +00:00
ApplicationBuilder {
parts: Some(ApplicationBuilderParts {
state: (),
2017-11-27 01:30:35 +00:00
prefix: prefix.into(),
2017-10-29 13:05:31 +00:00
default: Resource::default_not_found(),
2017-12-04 22:53:40 +00:00
routes: Vec::new(),
resources: HashMap::new(),
middlewares: Vec::new(),
})
2017-10-07 04:48:14 +00:00
}
}
}
2017-10-08 21:56:51 +00:00
impl<S> Application<S> where S: 'static {
2017-10-07 04:48:14 +00:00
2017-10-22 01:54:24 +00:00
/// Create application builder with specific state. State is shared with all
/// routes within same application and could be
/// accessed with `HttpContext::state()` method.
2017-11-27 01:30:35 +00:00
pub fn build<T: Into<String>>(prefix: T, state: S) -> ApplicationBuilder<S> {
2017-10-15 21:17:41 +00:00
ApplicationBuilder {
parts: Some(ApplicationBuilderParts {
state: state,
2017-11-27 01:30:35 +00:00
prefix: prefix.into(),
2017-10-29 13:05:31 +00:00
default: Resource::default_not_found(),
2017-12-04 22:53:40 +00:00
routes: Vec::new(),
resources: HashMap::new(),
middlewares: Vec::new(),
})
2017-10-15 21:17:41 +00:00
}
}
2017-10-07 04:48:14 +00:00
}
2017-10-15 21:17:41 +00:00
struct ApplicationBuilderParts<S> {
state: S,
2017-10-22 01:54:24 +00:00
prefix: String,
2017-10-15 21:17:41 +00:00
default: Resource<S>,
2017-12-04 22:53:40 +00:00
routes: Vec<(String, Route<S>)>,
2017-10-15 21:17:41 +00:00
resources: HashMap<String, Resource<S>>,
middlewares: Vec<Box<Middleware>>,
2017-10-15 21:17:41 +00:00
}
2017-11-27 01:30:35 +00:00
/// Structure that follows the builder pattern for building `Application` structs.
2017-10-15 21:17:41 +00:00
pub struct ApplicationBuilder<S=()> {
parts: Option<ApplicationBuilderParts<S>>,
}
impl<S> ApplicationBuilder<S> where S: 'static {
/// Configure resource for specific path.
///
2017-10-22 01:54:24 +00: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
2017-12-04 21:32:05 +00:00
/// in the `Params` object returned by `HttpRequest.match_info()` method.
2017-10-22 01:54:24 +00:00
///
/// By default, each part matches the regular expression `[^{}/]+`.
///
/// 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
/// store userid and friend in the exposed Params object:
///
2017-10-15 21:17:41 +00:00
/// ```rust
/// extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
2017-10-22 01:54:24 +00:00
/// let app = Application::default("/")
2017-10-15 21:17:41 +00:00
/// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
2017-10-15 21:17:41 +00:00
/// })
/// .finish();
/// }
/// ```
2017-11-27 01:30:35 +00:00
pub fn resource<F, P: Into<String>>(&mut self, path: P, f: F) -> &mut Self
2017-10-15 21:17:41 +00:00
where F: FnOnce(&mut Resource<S>) + 'static
{
{
let parts = self.parts.as_mut().expect("Use after finish");
// add resource
2017-11-27 01:30:35 +00:00
let path = path.into();
2017-10-15 21:17:41 +00:00
if !parts.resources.contains_key(&path) {
2017-10-17 02:21:24 +00:00
check_pattern(&path);
2017-10-15 21:17:41 +00:00
parts.resources.insert(path.clone(), Resource::default());
}
f(parts.resources.get_mut(&path).unwrap());
}
self
}
2017-11-29 21:26:55 +00:00
/// Default resource is used if no match route could be found.
2017-10-15 21:17:41 +00:00
pub fn default_resource<F>(&mut self, f: F) -> &mut Self
where F: FnOnce(&mut Resource<S>) + 'static
{
{
let parts = self.parts.as_mut().expect("Use after finish");
f(&mut parts.default);
}
self
}
2017-12-04 22:53:40 +00:00
/// Register a middleware
pub fn middleware<T>(&mut self, mw: T) -> &mut Self
where T: Middleware + 'static
{
self.parts.as_mut().expect("Use after finish")
.middlewares.push(Box::new(mw));
self
}
2017-10-15 21:17:41 +00:00
/// Construct application
pub fn finish(&mut self) -> Application<S> {
2017-10-22 01:54:24 +00:00
let parts = self.parts.take().expect("Use after finish");
let prefix = if parts.prefix.ends_with('/') {
parts.prefix
} else {
parts.prefix + "/"
};
2017-12-04 22:53:40 +00:00
let mut routes = Vec::new();
for (path, route) in parts.routes {
routes.push((prefix.clone() + path.trim_left_matches('/'), route));
2017-10-22 01:54:24 +00:00
}
Application {
state: Rc::new(parts.state),
prefix: prefix.clone(),
default: parts.default,
2017-12-04 22:53:40 +00:00
routes: routes,
2017-12-05 19:31:35 +00:00
router: Router::new(prefix, parts.resources),
middlewares: Rc::new(parts.middlewares),
}
2017-10-15 21:17:41 +00:00
}
}
2017-10-07 04:48:14 +00:00
2017-10-22 01:54:24 +00:00
impl<S: 'static> From<ApplicationBuilder<S>> for Application<S> {
fn from(mut builder: ApplicationBuilder<S>) -> Application<S> {
builder.finish()
}
2017-10-07 04:48:14 +00:00
}
2017-10-22 01:54:24 +00:00
impl<S: 'static> Iterator for ApplicationBuilder<S> {
type Item = Application<S>;
2017-10-07 04:48:14 +00:00
2017-10-22 01:54:24 +00:00
fn next(&mut self) -> Option<Self::Item> {
if self.parts.is_some() {
Some(self.finish())
2017-10-07 04:48:14 +00:00
} else {
2017-10-22 01:54:24 +00:00
None
2017-10-07 04:48:14 +00:00
}
}
}