1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-04 23:36:34 +00:00
actix-web/src/application.rs

362 lines
11 KiB
Rust
Raw Normal View History

2017-10-07 04:48:14 +00:00
use std::rc::Rc;
use std::collections::HashMap;
2017-12-12 00:26:51 +00:00
use handler::Reply;
use router::{Router, Pattern};
2017-12-05 00:09:22 +00:00
use resource::Resource;
use httprequest::HttpRequest;
2017-12-09 12:33:40 +00:00
use channel::{HttpHandler, IntoHttpHandler, HttpHandlerTask};
2017-11-25 06:15:52 +00:00
use pipeline::Pipeline;
2017-11-10 06:08:54 +00:00
use middlewares::Middleware;
use server::ServerSettings;
2017-10-07 04:48:14 +00:00
/// Application
2017-12-15 04:29:49 +00:00
pub struct HttpApplication<S=()> {
2017-10-22 01:54:24 +00:00
state: Rc<S>,
prefix: String,
2017-10-08 21:56:51 +00:00
default: Resource<S>,
2017-12-05 19:31:35 +00:00
router: Router<S>,
2017-12-09 12:33:40 +00:00
middlewares: Rc<Vec<Box<Middleware<S>>>>,
2017-10-07 04:48:14 +00:00
}
2017-12-12 16:51:16 +00:00
impl<S: 'static> HttpApplication<S> {
2017-10-07 04:48:14 +00:00
2017-12-09 21:25:06 +00:00
pub(crate) fn prepare_request(&self, req: HttpRequest) -> HttpRequest<S> {
req.with_state(Rc::clone(&self.state), self.router.clone())
}
pub(crate) fn run(&self, mut req: HttpRequest<S>) -> Reply {
if let Some(h) = self.router.recognize(&mut req) {
2017-12-12 00:26:51 +00:00
h.handle(req.clone(), Some(&self.default))
2017-10-22 01:54:24 +00:00
} else {
2017-12-12 00:26:51 +00:00
self.default.handle(req, None)
2017-10-10 06:07:32 +00:00
}
2017-10-07 04:48:14 +00:00
}
}
2017-12-12 16:51:16 +00:00
impl<S: 'static> HttpHandler for HttpApplication<S> {
2017-12-09 12:33:40 +00:00
fn handle(&self, req: HttpRequest) -> Result<Box<HttpHandlerTask>, HttpRequest> {
2017-11-29 21:53:52 +00:00
if req.path().starts_with(&self.prefix) {
2017-12-09 21:25:06 +00:00
let req = self.prepare_request(req);
2017-12-09 12:33:40 +00:00
Ok(Box::new(Pipeline::new(req, Rc::clone(&self.middlewares),
&|req: HttpRequest<S>| self.run(req))))
2017-11-29 21:53:52 +00:00
} else {
Err(req)
}
}
fn server_settings(&mut self, settings: ServerSettings) {
self.router.set_server_settings(settings);
}
}
2017-12-06 19:00:39 +00:00
struct ApplicationParts<S> {
state: S,
prefix: String,
default: Resource<S>,
resources: HashMap<Pattern, Option<Resource<S>>>,
external: HashMap<String, Pattern>,
2017-12-09 12:33:40 +00:00
middlewares: Vec<Box<Middleware<S>>>,
2017-12-06 19:00:39 +00:00
}
/// Structure that follows the builder pattern for building `Application` structs.
pub struct Application<S=()> {
parts: Option<ApplicationParts<S>>,
}
2017-10-15 21:17:41 +00:00
impl Application<()> {
2017-12-06 19:00:39 +00:00
/// Create application with empty state. Application can
/// be configured with builder-like pattern.
pub fn new() -> Application<()> {
2017-12-06 19:00:39 +00:00
Application {
parts: Some(ApplicationParts {
2017-10-15 21:17:41 +00:00
state: (),
prefix: "/".to_owned(),
2017-10-29 13:05:31 +00:00
default: Resource::default_not_found(),
resources: HashMap::new(),
external: HashMap::new(),
middlewares: Vec::new(),
})
2017-10-07 04:48:14 +00:00
}
}
}
impl Default for Application<()> {
fn default() -> Self {
Application::new()
}
}
2017-12-12 16:51:16 +00:00
impl<S> Application<S> where S: 'static {
2017-10-07 04:48:14 +00:00
2017-12-06 19:00:39 +00: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(state: S) -> Application<S> {
2017-12-06 19:00:39 +00:00
Application {
parts: Some(ApplicationParts {
2017-10-15 21:17:41 +00:00
state: state,
prefix: "/".to_owned(),
2017-10-29 13:05:31 +00:00
default: Resource::default_not_found(),
resources: HashMap::new(),
external: HashMap::new(),
middlewares: Vec::new(),
})
2017-10-15 21:17:41 +00:00
}
}
/// Set application prefix.
///
/// Only requests that matches application's prefix get processed by this application.
/// Application prefix always contains laading "/" slash. If supplied prefix
/// does not contain leading slash, it get inserted.
///
/// Inthe following example only requests with "/app/" path prefix
/// get handled. Request with path "/app/test/" will be handled,
/// but request with path "/other/..." will return *NOT FOUND*
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::new()
/// .prefix("/app")
/// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HTTPOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HTTPMethodNotAllowed);
/// })
/// .finish();
/// }
/// ```
pub fn prefix<P: Into<String>>(mut self, prefix: P) -> Application<S> {
{
let parts = self.parts.as_mut().expect("Use after finish");
let mut prefix = prefix.into();
if !prefix.starts_with('/') {
prefix.insert(0, '/')
}
parts.prefix = prefix;
}
self
}
2017-10-15 21:17:41 +00:00
/// 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
2017-12-06 19:00:39 +00:00
/// # extern crate actix_web;
2017-10-15 21:17:41 +00:00
/// use actix_web::*;
///
/// fn main() {
/// let app = Application::new()
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();
/// }
/// ```
pub fn resource<F>(mut self, path: &str, f: F) -> Application<S>
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
let mut resource = Resource::default();
f(&mut resource);
let pattern = Pattern::new(resource.get_name(), path);
if parts.resources.contains_key(&pattern) {
panic!("Resource {:?} is registered.", path);
2017-10-15 21:17:41 +00:00
}
parts.resources.insert(pattern, Some(resource));
2017-10-15 21:17:41 +00:00
}
self
}
2017-12-12 00:26:51 +00:00
/// Default resource is used if no matched route could be found.
pub fn default_resource<F>(mut self, f: F) -> Application<S>
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");
f(&mut parts.default);
}
self
}
/// Register external resource.
///
/// External resources are useful for URL generation purposes only and
/// are never considered for matching at request time.
/// Call to `HttpRequest::url_for()` will work as expected.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::*;
///
/// fn index(mut req: HttpRequest) -> Result<HttpResponse> {
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
/// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
/// Ok(httpcodes::HTTPOk.into())
/// }
///
/// fn main() {
/// let app = Application::new()
/// .resource("/index.html", |r| r.f(index))
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
/// .finish();
/// }
/// ```
pub fn external_resource<T, U>(mut self, name: T, url: U) -> Application<S>
where T: AsRef<str>, U: AsRef<str>
{
{
let parts = self.parts.as_mut().expect("Use after finish");
if parts.external.contains_key(name.as_ref()) {
panic!("External resource {:?} is registered.", name.as_ref());
}
parts.external.insert(
String::from(name.as_ref()), Pattern::new(name.as_ref(), url.as_ref()));
}
self
}
2017-12-04 22:53:40 +00:00
/// Register a middleware
pub fn middleware<T>(mut self, mw: T) -> Application<S>
2017-12-09 12:33:40 +00:00
where T: Middleware<S> + 'static
{
self.parts.as_mut().expect("Use after finish")
.middlewares.push(Box::new(mw));
self
}
2017-12-06 19:00:39 +00:00
/// Finish application configuration and create HttpHandler object
pub fn finish(&mut self) -> HttpApplication<S> {
2017-10-22 01:54:24 +00:00
let parts = self.parts.take().expect("Use after finish");
2017-12-07 00:26:27 +00:00
let prefix = parts.prefix.trim().trim_right_matches('/');
let mut resources = parts.resources;
for (_, pattern) in parts.external {
resources.insert(pattern, None);
}
2017-12-06 19:00:39 +00:00
HttpApplication {
2017-10-22 01:54:24 +00:00
state: Rc::new(parts.state),
2017-12-07 00:26:27 +00:00
prefix: prefix.to_owned(),
2017-10-22 01:54:24 +00:00
default: parts.default,
router: Router::new(prefix, resources),
middlewares: Rc::new(parts.middlewares),
}
2017-10-15 21:17:41 +00:00
}
}
2017-10-07 04:48:14 +00:00
2017-12-12 16:51:16 +00:00
impl<S: 'static> IntoHttpHandler for Application<S> {
2017-12-06 19:00:39 +00:00
type Handler = HttpApplication<S>;
fn into_handler(mut self) -> HttpApplication<S> {
self.finish()
}
}
2017-12-12 16:51:16 +00:00
impl<'a, S: 'static> IntoHttpHandler for &'a mut Application<S> {
2017-12-06 19:00:39 +00:00
type Handler = HttpApplication<S>;
fn into_handler(self) -> HttpApplication<S> {
self.finish()
2017-10-22 01:54:24 +00:00
}
2017-10-07 04:48:14 +00:00
}
2017-12-06 19:00:39 +00:00
#[doc(hidden)]
2017-12-12 16:51:16 +00:00
impl<S: 'static> Iterator for Application<S> {
2017-12-06 19:00:39 +00:00
type Item = HttpApplication<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
}
}
}
2017-12-06 21:02:53 +00:00
#[cfg(test)]
mod tests {
use std::str::FromStr;
use http::{Method, Version, Uri, HeaderMap, StatusCode};
use super::*;
use httprequest::HttpRequest;
use httpcodes;
#[test]
fn test_default_resource() {
let app = Application::new()
2017-12-06 21:02:53 +00:00
.resource("/test", |r| r.h(httpcodes::HTTPOk))
.finish();
let req = HttpRequest::new(
Method::GET, Uri::from_str("/test").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, HeaderMap::new(), None);
2017-12-09 21:25:06 +00:00
let resp = app.run(req);
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
2017-12-06 21:02:53 +00:00
let req = HttpRequest::new(
Method::GET, Uri::from_str("/blah").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, HeaderMap::new(), None);
2017-12-09 21:25:06 +00:00
let resp = app.run(req);
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
2017-12-06 21:02:53 +00:00
let app = Application::new()
2017-12-06 21:02:53 +00:00
.default_resource(|r| r.h(httpcodes::HTTPMethodNotAllowed))
.finish();
let req = HttpRequest::new(
Method::GET, Uri::from_str("/blah").unwrap(),
2017-12-13 16:00:25 +00:00
Version::HTTP_11, HeaderMap::new(), None);
2017-12-09 21:25:06 +00:00
let resp = app.run(req);
assert_eq!(resp.as_response().unwrap().status(), StatusCode::METHOD_NOT_ALLOWED);
2017-12-06 21:02:53 +00:00
}
2017-12-07 02:39:13 +00:00
#[test]
fn test_unhandled_prefix() {
let app = Application::new()
.prefix("/test")
2017-12-07 02:39:13 +00:00
.resource("/test", |r| r.h(httpcodes::HTTPOk))
.finish();
assert!(app.handle(HttpRequest::default()).is_err());
}
#[test]
fn test_state() {
let app = Application::with_state(10)
2017-12-07 02:39:13 +00:00
.resource("/", |r| r.h(httpcodes::HTTPOk))
.finish();
2017-12-09 12:33:40 +00:00
let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone());
2017-12-09 21:25:06 +00:00
let resp = app.run(req);
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
2017-12-07 02:39:13 +00:00
}
2017-12-06 21:02:53 +00:00
}