1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 09:42:40 +01:00
actix-extras/src/application.rs

310 lines
9.5 KiB
Rust
Raw Normal View History

2017-10-07 06:48:14 +02:00
use std::rc::Rc;
use std::collections::HashMap;
2017-12-05 22:31:06 +01:00
use error::UriGenerationError;
2017-12-04 23:53:40 +01:00
use handler::{Reply, RouteHandler};
2017-12-05 01:09:22 +01:00
use resource::Resource;
2017-12-05 22:31:06 +01:00
use recognizer::{RouteRecognizer, check_pattern, PatternElement};
use httprequest::HttpRequest;
2017-12-06 20:00:39 +01:00
use channel::{HttpHandler, IntoHttpHandler};
2017-11-25 07:15:52 +01:00
use pipeline::Pipeline;
2017-11-10 07:08:54 +01:00
use middlewares::Middleware;
2017-10-07 06:48:14 +02:00
2017-12-05 20:31:35 +01: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 22:31:06 +01: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 20:31:35 +01:00
}
2017-10-07 06:48:14 +02:00
/// Application
2017-12-06 20:00:39 +01:00
pub struct HttpApplication<S> {
2017-10-22 03:54:24 +02:00
state: Rc<S>,
prefix: String,
2017-10-08 23:56:51 +02:00
default: Resource<S>,
2017-12-05 20:31:35 +01:00
router: Router<S>,
middlewares: Rc<Vec<Box<Middleware>>>,
2017-10-07 06:48:14 +02:00
}
2017-12-06 20:00:39 +01:00
impl<S: 'static> HttpApplication<S> {
2017-10-07 06:48:14 +02:00
2017-12-01 00:13:56 +01:00
fn run(&self, req: HttpRequest) -> Reply {
2017-11-27 06:18:38 +01:00
let mut req = req.with_state(Rc::clone(&self.state));
2017-12-05 20:31:35 +01:00
if let Some((params, h)) = self.router.0.recognize(req.path()) {
2017-10-22 03:54:24 +02:00
if let Some(params) = params {
req.set_match_info(params);
2017-12-06 20:00:39 +01:00
req.set_prefix(self.router.0.prefix());
2017-10-22 03:54:24 +02:00
}
2017-12-01 00:13:56 +01:00
h.handle(req)
2017-10-22 03:54:24 +02:00
} else {
2017-12-01 00:13:56 +01:00
self.default.handle(req)
2017-10-10 08:07:32 +02:00
}
2017-10-07 06:48:14 +02:00
}
}
2017-12-06 20:00:39 +01:00
impl<S: 'static> HttpHandler for HttpApplication<S> {
2017-11-29 22:53:52 +01: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-12-01 00:13:56 +01:00
&|req: HttpRequest| self.run(req)))
2017-11-29 22:53:52 +01:00
} else {
Err(req)
}
}
}
2017-12-06 20:00:39 +01:00
struct ApplicationParts<S> {
state: S,
prefix: String,
default: Resource<S>,
resources: HashMap<String, Resource<S>>,
middlewares: Vec<Box<Middleware>>,
}
/// Structure that follows the builder pattern for building `Application` structs.
pub struct Application<S=()> {
parts: Option<ApplicationParts<S>>,
}
2017-10-15 23:17:41 +02:00
impl Application<()> {
2017-12-06 20:00:39 +01:00
/// Create application with empty state. Application can
/// be configured with builder-like pattern.
///
/// This method accepts path prefix for which it should serve requests.
pub fn new<T: Into<String>>(prefix: T) -> Application<()> {
Application {
parts: Some(ApplicationParts {
2017-10-15 23:17:41 +02:00
state: (),
2017-11-27 02:30:35 +01:00
prefix: prefix.into(),
2017-10-29 14:05:31 +01:00
default: Resource::default_not_found(),
resources: HashMap::new(),
middlewares: Vec::new(),
})
2017-10-07 06:48:14 +02:00
}
}
}
2017-10-08 23:56:51 +02:00
impl<S> Application<S> where S: 'static {
2017-10-07 06:48:14 +02:00
2017-12-06 20:00:39 +01:00
/// Create application with specific state. Application can be
/// configured with builder-like pattern.
///
/// State is shared with all reousrces within same application and could be
/// accessed with `HttpRequest::state()` method.
pub fn with_state<T: Into<String>>(prefix: T, state: S) -> Application<S> {
Application {
parts: Some(ApplicationParts {
2017-10-15 23:17:41 +02:00
state: state,
2017-11-27 02:30:35 +01:00
prefix: prefix.into(),
2017-10-29 14:05:31 +01:00
default: Resource::default_not_found(),
resources: HashMap::new(),
middlewares: Vec::new(),
})
2017-10-15 23:17:41 +02:00
}
}
/// Configure resource for specific path.
///
2017-10-22 03:54: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
2017-12-04 22:32:05 +01:00
/// in the `Params` object returned by `HttpRequest.match_info()` method.
2017-10-22 03:54:24 +02: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 23:17:41 +02:00
/// ```rust
2017-12-06 20:00:39 +01:00
/// # extern crate actix_web;
2017-10-15 23:17:41 +02:00
/// use actix_web::*;
///
/// fn main() {
2017-12-06 20:00:39 +01:00
/// let app = Application::new("/")
2017-10-15 23:17:41 +02:00
/// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
2017-10-15 23:17:41 +02:00
/// })
/// .finish();
/// }
/// ```
2017-11-27 02:30:35 +01:00
pub fn resource<F, P: Into<String>>(&mut self, path: P, f: F) -> &mut Self
2017-10-15 23:17:41 +02:00
where F: FnOnce(&mut Resource<S>) + 'static
{
{
let parts = self.parts.as_mut().expect("Use after finish");
// add resource
2017-11-27 02:30:35 +01:00
let path = path.into();
2017-10-15 23:17:41 +02:00
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());
}
f(parts.resources.get_mut(&path).unwrap());
}
self
}
2017-11-29 22:26:55 +01:00
/// Default resource is used if no match route could be found.
2017-10-15 23:17:41 +02: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 23:53:40 +01: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-12-06 20:00:39 +01:00
/// Finish application configuration and create HttpHandler object
pub fn finish(&mut self) -> HttpApplication<S> {
2017-10-22 03:54:24 +02:00
let parts = self.parts.take().expect("Use after finish");
let prefix = if parts.prefix.ends_with('/') {
parts.prefix
} else {
parts.prefix + "/"
};
2017-12-06 20:00:39 +01:00
HttpApplication {
2017-10-22 03:54:24 +02:00
state: Rc::new(parts.state),
prefix: prefix.clone(),
default: parts.default,
2017-12-05 20:31:35 +01:00
router: Router::new(prefix, parts.resources),
middlewares: Rc::new(parts.middlewares),
}
2017-10-15 23:17:41 +02:00
}
}
2017-10-07 06:48:14 +02:00
2017-12-06 20:00:39 +01:00
impl<S: 'static> IntoHttpHandler for Application<S> {
type Handler = HttpApplication<S>;
fn into_handler(mut self) -> HttpApplication<S> {
self.finish()
}
}
impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
type Handler = HttpApplication<S>;
fn into_handler(self) -> HttpApplication<S> {
self.finish()
2017-10-22 03:54:24 +02:00
}
2017-10-07 06:48:14 +02:00
}
2017-12-06 20:00:39 +01:00
#[doc(hidden)]
impl<S: 'static> Iterator for Application<S> {
type Item = HttpApplication<S>;
2017-10-07 06:48:14 +02:00
2017-10-22 03:54:24 +02:00
fn next(&mut self) -> Option<Self::Item> {
if self.parts.is_some() {
Some(self.finish())
2017-10-07 06:48:14 +02:00
} else {
2017-10-22 03:54:24 +02:00
None
2017-10-07 06:48:14 +02:00
}
}
}
2017-12-06 22:02:53 +01:00
#[cfg(test)]
mod tests {
use std::str::FromStr;
use http::{Method, Version, Uri, HeaderMap, StatusCode};
use super::*;
use handler::ReplyItem;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use payload::Payload;
use httpcodes;
impl Reply {
fn msg(self) -> Option<HttpResponse> {
match self.into() {
ReplyItem::Message(resp) => Some(resp),
_ => None,
}
}
}
#[test]
fn test_default_resource() {
let app = Application::new("/")
.resource("/test", |r| r.h(httpcodes::HTTPOk))
.finish();
let req = HttpRequest::new(
Method::GET, Uri::from_str("/test").unwrap(),
Version::HTTP_11, HeaderMap::new(), Payload::empty());
let resp = app.run(req).msg().unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = HttpRequest::new(
Method::GET, Uri::from_str("/blah").unwrap(),
Version::HTTP_11, HeaderMap::new(), Payload::empty());
let resp = app.run(req).msg().unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let app = Application::new("/")
.default_resource(|r| r.h(httpcodes::HTTPMethodNotAllowed))
.finish();
let req = HttpRequest::new(
Method::GET, Uri::from_str("/blah").unwrap(),
Version::HTTP_11, HeaderMap::new(), Payload::empty());
let resp = app.run(req).msg().unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}
}