2018-01-03 00:23:31 +01:00
|
|
|
use std::mem;
|
2017-10-07 06:48:14 +02:00
|
|
|
use std::rc::Rc;
|
2018-04-02 19:27:37 +02:00
|
|
|
use std::cell::UnsafeCell;
|
2017-10-07 06:48:14 +02:00
|
|
|
use std::collections::HashMap;
|
|
|
|
|
2017-12-12 01:26:51 +01:00
|
|
|
use handler::Reply;
|
2018-04-02 02:37:22 +02:00
|
|
|
use router::{Router, Resource};
|
|
|
|
use resource::{ResourceHandler};
|
2018-03-29 20:06:44 +02:00
|
|
|
use header::ContentEncoding;
|
2018-01-02 22:09:02 +01:00
|
|
|
use handler::{Handler, RouteHandler, WrapHandler};
|
2017-10-15 07:52:38 +02:00
|
|
|
use httprequest::HttpRequest;
|
2018-04-02 19:27:37 +02:00
|
|
|
use pipeline::{Pipeline, PipelineHandler, HandlerType};
|
2017-12-27 04:59:41 +01:00
|
|
|
use middleware::Middleware;
|
2018-01-12 03:35:05 +01:00
|
|
|
use server::{HttpHandler, IntoHttpHandler, HttpHandlerTask, ServerSettings};
|
2017-10-07 06:48:14 +02:00
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
#[deprecated(since="0.5.0", note="please use `actix_web::App` instead")]
|
|
|
|
pub type Application<S> = App<S>;
|
|
|
|
|
2017-10-07 06:48:14 +02:00
|
|
|
/// Application
|
2017-12-15 05:29:49 +01:00
|
|
|
pub struct HttpApplication<S=()> {
|
2017-10-22 03:54:24 +02:00
|
|
|
state: Rc<S>,
|
|
|
|
prefix: String,
|
2017-12-26 18:00:45 +01:00
|
|
|
router: Router,
|
2018-04-02 19:27:37 +02:00
|
|
|
inner: Rc<UnsafeCell<Inner<S>>>,
|
2017-12-09 13:33:40 +01:00
|
|
|
middlewares: Rc<Vec<Box<Middleware<S>>>>,
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2017-12-29 10:01:31 +01:00
|
|
|
pub(crate) struct Inner<S> {
|
2018-01-03 00:23:31 +01:00
|
|
|
prefix: usize,
|
2018-04-02 02:37:22 +02:00
|
|
|
default: ResourceHandler<S>,
|
2018-02-19 07:23:17 +01:00
|
|
|
encoding: ContentEncoding,
|
2018-04-02 02:37:22 +02:00
|
|
|
resources: Vec<ResourceHandler<S>>,
|
2018-01-02 22:09:02 +01:00
|
|
|
handlers: Vec<(String, Box<RouteHandler<S>>)>,
|
2017-12-29 10:01:31 +01:00
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
|
2017-12-29 10:01:31 +01:00
|
|
|
impl<S: 'static> PipelineHandler<S> for Inner<S> {
|
2017-12-09 22:25:06 +01:00
|
|
|
|
2018-02-19 07:23:17 +01:00
|
|
|
fn encoding(&self) -> ContentEncoding {
|
|
|
|
self.encoding
|
|
|
|
}
|
|
|
|
|
2018-04-02 19:27:37 +02:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>, htype: HandlerType) -> Reply {
|
|
|
|
match htype {
|
|
|
|
HandlerType::Normal(idx) =>
|
|
|
|
self.resources[idx].handle(req, Some(&mut self.default)),
|
|
|
|
HandlerType::Handler(idx) =>
|
|
|
|
self.handlers[idx].1.handle(req),
|
|
|
|
HandlerType::Default =>
|
|
|
|
self.default.handle(req, None)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S: 'static> HttpApplication<S> {
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn as_ref(&self) -> &Inner<S> {
|
|
|
|
unsafe{&*self.inner.get()}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn get_handler(&self, req: &mut HttpRequest<S>) -> HandlerType {
|
|
|
|
if let Some(idx) = self.router.recognize(req) {
|
|
|
|
HandlerType::Normal(idx)
|
2017-10-22 03:54:24 +02:00
|
|
|
} else {
|
2018-04-02 19:27:37 +02:00
|
|
|
let inner = self.as_ref();
|
|
|
|
for idx in 0..inner.handlers.len() {
|
|
|
|
let &(ref prefix, _) = &inner.handlers[idx];
|
2018-01-02 22:09:02 +01:00
|
|
|
let m = {
|
2018-04-02 19:27:37 +02:00
|
|
|
let path = &req.path()[inner.prefix..];
|
2018-03-07 23:56:53 +01:00
|
|
|
path.starts_with(prefix) && (
|
|
|
|
path.len() == prefix.len() ||
|
|
|
|
path.split_at(prefix.len()).1.starts_with('/'))
|
2018-01-02 22:09:02 +01:00
|
|
|
};
|
|
|
|
if m {
|
2018-01-10 05:00:18 +01:00
|
|
|
let path: &'static str = unsafe {
|
2018-04-02 19:27:37 +02:00
|
|
|
mem::transmute(&req.path()[inner.prefix+prefix.len()..]) };
|
2018-01-03 00:23:31 +01:00
|
|
|
if path.is_empty() {
|
|
|
|
req.match_info_mut().add("tail", "");
|
|
|
|
} else {
|
2018-01-04 03:21:34 +01:00
|
|
|
req.match_info_mut().add("tail", path.split_at(1).1);
|
2018-01-03 00:23:31 +01:00
|
|
|
}
|
2018-04-02 19:27:37 +02:00
|
|
|
return HandlerType::Handler(idx)
|
2018-01-02 22:09:02 +01:00
|
|
|
}
|
|
|
|
}
|
2018-04-02 19:27:37 +02:00
|
|
|
HandlerType::Default
|
2017-10-10 08:07:32 +02:00
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2018-02-19 23:27:36 +01:00
|
|
|
#[cfg(test)]
|
2018-04-02 19:27:37 +02:00
|
|
|
pub(crate) fn run(&mut self, mut req: HttpRequest<S>) -> Reply {
|
|
|
|
let tp = self.get_handler(&mut req);
|
|
|
|
unsafe{&mut *self.inner.get()}.handle(req, tp)
|
2017-12-29 10:01:31 +01:00
|
|
|
}
|
2018-04-02 19:27:37 +02:00
|
|
|
|
2018-01-14 03:58:17 +01:00
|
|
|
#[cfg(test)]
|
2017-12-29 10:01:31 +01:00
|
|
|
pub(crate) fn prepare_request(&self, req: HttpRequest) -> HttpRequest<S> {
|
|
|
|
req.with_state(Rc::clone(&self.state), self.router.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-12 17:51:16 +01:00
|
|
|
impl<S: 'static> HttpHandler for HttpApplication<S> {
|
2017-10-22 07:59:09 +02:00
|
|
|
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest) -> Result<Box<HttpHandlerTask>, HttpRequest> {
|
2017-12-29 23:04:13 +01:00
|
|
|
let m = {
|
|
|
|
let path = req.path();
|
|
|
|
path.starts_with(&self.prefix) && (
|
|
|
|
path.len() == self.prefix.len() ||
|
|
|
|
path.split_at(self.prefix.len()).1.starts_with('/'))
|
|
|
|
};
|
|
|
|
if m {
|
2018-04-02 19:27:37 +02:00
|
|
|
let mut req = req.with_state(Rc::clone(&self.state), self.router.clone());
|
|
|
|
let tp = self.get_handler(&mut req);
|
2017-12-29 10:01:31 +01:00
|
|
|
let inner = Rc::clone(&self.inner);
|
2018-04-02 19:27:37 +02:00
|
|
|
Ok(Box::new(Pipeline::new(req, Rc::clone(&self.middlewares), inner, tp)))
|
2017-11-29 22:53:52 +01:00
|
|
|
} else {
|
|
|
|
Err(req)
|
|
|
|
}
|
2017-10-22 07:59:09 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-06 20:00:39 +01:00
|
|
|
struct ApplicationParts<S> {
|
|
|
|
state: S,
|
|
|
|
prefix: String,
|
2017-12-29 20:33:04 +01:00
|
|
|
settings: ServerSettings,
|
2018-04-02 02:37:22 +02:00
|
|
|
default: ResourceHandler<S>,
|
|
|
|
resources: Vec<(Resource, Option<ResourceHandler<S>>)>,
|
2018-01-02 22:09:02 +01:00
|
|
|
handlers: Vec<(String, Box<RouteHandler<S>>)>,
|
2018-04-02 02:37:22 +02:00
|
|
|
external: HashMap<String, Resource>,
|
2018-02-19 07:23:17 +01:00
|
|
|
encoding: ContentEncoding,
|
2017-12-09 13:33:40 +01:00
|
|
|
middlewares: Vec<Box<Middleware<S>>>,
|
2017-12-06 20:00:39 +01:00
|
|
|
}
|
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
/// Structure that follows the builder pattern for building application instances.
|
|
|
|
pub struct App<S=()> {
|
2017-12-06 20:00:39 +01:00
|
|
|
parts: Option<ApplicationParts<S>>,
|
|
|
|
}
|
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
impl App<()> {
|
2017-10-15 23:17:41 +02:00
|
|
|
|
2017-12-06 20:00:39 +01:00
|
|
|
/// Create application with empty state. Application can
|
|
|
|
/// be configured with builder-like pattern.
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn new() -> App<()> {
|
|
|
|
App {
|
2017-12-06 20:00:39 +01:00
|
|
|
parts: Some(ApplicationParts {
|
2017-10-15 23:17:41 +02:00
|
|
|
state: (),
|
2017-12-11 23:16:29 +01:00
|
|
|
prefix: "/".to_owned(),
|
2017-12-29 20:33:04 +01:00
|
|
|
settings: ServerSettings::default(),
|
2018-04-02 02:37:22 +02:00
|
|
|
default: ResourceHandler::default_not_found(),
|
2018-02-22 14:48:18 +01:00
|
|
|
resources: Vec::new(),
|
2018-01-02 22:09:02 +01:00
|
|
|
handlers: Vec::new(),
|
2017-12-08 01:22:26 +01:00
|
|
|
external: HashMap::new(),
|
2018-02-19 07:23:17 +01:00
|
|
|
encoding: ContentEncoding::Auto,
|
2017-10-22 07:59:09 +02:00
|
|
|
middlewares: Vec::new(),
|
|
|
|
})
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
impl Default for App<()> {
|
2017-12-11 23:16:29 +01:00
|
|
|
fn default() -> Self {
|
2018-03-31 09:16:55 +02:00
|
|
|
App::new()
|
2017-12-11 23:16:29 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
impl<S> App<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.
|
|
|
|
///
|
2018-01-15 22:47:25 +01:00
|
|
|
/// State is shared with all resources within same application and could be
|
2017-12-06 20:00:39 +01:00
|
|
|
/// accessed with `HttpRequest::state()` method.
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn with_state(state: S) -> App<S> {
|
|
|
|
App {
|
2017-12-06 20:00:39 +01:00
|
|
|
parts: Some(ApplicationParts {
|
2018-02-26 23:33:56 +01:00
|
|
|
state,
|
2017-12-11 23:16:29 +01:00
|
|
|
prefix: "/".to_owned(),
|
2017-12-29 20:33:04 +01:00
|
|
|
settings: ServerSettings::default(),
|
2018-04-02 02:37:22 +02:00
|
|
|
default: ResourceHandler::default_not_found(),
|
2018-02-22 14:48:18 +01:00
|
|
|
resources: Vec::new(),
|
2018-01-02 22:09:02 +01:00
|
|
|
handlers: Vec::new(),
|
2017-12-08 01:22:26 +01:00
|
|
|
external: HashMap::new(),
|
2017-10-22 07:59:09 +02:00
|
|
|
middlewares: Vec::new(),
|
2018-02-19 07:23:17 +01:00
|
|
|
encoding: ContentEncoding::Auto,
|
2017-10-22 07:59:09 +02:00
|
|
|
})
|
2017-10-15 23:17:41 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-01 02:26:32 +01:00
|
|
|
/// Set application prefix
|
2017-12-11 23:16:29 +01:00
|
|
|
///
|
|
|
|
/// Only requests that matches application's prefix get processed by this application.
|
2018-01-16 19:59:33 +01:00
|
|
|
/// Application prefix always contains leading "/" slash. If supplied prefix
|
2017-12-29 23:04:13 +01:00
|
|
|
/// does not contain leading slash, it get inserted. Prefix should
|
2018-01-02 22:09:02 +01:00
|
|
|
/// consists valid path segments. i.e for application with
|
2017-12-29 23:04:13 +01:00
|
|
|
/// prefix `/app` any request with following paths `/app`, `/app/` or `/app/test`
|
|
|
|
/// would match, but path `/application` would not match.
|
2017-12-11 23:16:29 +01:00
|
|
|
///
|
2017-12-29 23:04:13 +01:00
|
|
|
/// In the following example only requests with "/app/" path prefix
|
|
|
|
/// get handled. Request with path "/app/test/" would be handled,
|
|
|
|
/// but request with path "/application" or "/other/..." would return *NOT FOUND*
|
2017-12-11 23:16:29 +01:00
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
2018-03-31 09:16:55 +02:00
|
|
|
/// use actix_web::{http, App, HttpResponse};
|
2017-12-11 23:16:29 +01:00
|
|
|
///
|
|
|
|
/// fn main() {
|
2018-03-31 09:16:55 +02:00
|
|
|
/// let app = App::new()
|
2017-12-11 23:16:29 +01:00
|
|
|
/// .prefix("/app")
|
|
|
|
/// .resource("/test", |r| {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
|
|
|
|
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
|
2017-12-11 23:16:29 +01:00
|
|
|
/// })
|
|
|
|
/// .finish();
|
|
|
|
/// }
|
|
|
|
/// ```
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn prefix<P: Into<String>>(mut self, prefix: P) -> App<S> {
|
2017-12-11 23:16:29 +01:00
|
|
|
{
|
|
|
|
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 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;
|
2018-03-31 09:16:55 +02:00
|
|
|
/// use actix_web::{http, App, HttpResponse};
|
2017-10-15 23:17:41 +02:00
|
|
|
///
|
|
|
|
/// fn main() {
|
2018-03-31 09:16:55 +02:00
|
|
|
/// let app = App::new()
|
2017-10-15 23:17:41 +02:00
|
|
|
/// .resource("/test", |r| {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
|
|
|
|
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
|
2018-01-02 22:09:02 +01:00
|
|
|
/// });
|
2017-10-15 23:17:41 +02:00
|
|
|
/// }
|
|
|
|
/// ```
|
2018-04-04 07:06:18 +02:00
|
|
|
pub fn resource<F, R>(mut self, path: &str, f: F) -> App<S>
|
|
|
|
where F: FnOnce(&mut ResourceHandler<S>) -> R + 'static
|
2017-10-15 23:17:41 +02:00
|
|
|
{
|
|
|
|
{
|
|
|
|
let parts = self.parts.as_mut().expect("Use after finish");
|
|
|
|
|
|
|
|
// add resource
|
2018-04-02 02:37:22 +02:00
|
|
|
let mut resource = ResourceHandler::default();
|
2017-12-08 01:22:26 +01:00
|
|
|
f(&mut resource);
|
|
|
|
|
2018-04-02 02:37:22 +02:00
|
|
|
let pattern = Resource::new(resource.get_name(), path);
|
2018-02-22 14:48:18 +01:00
|
|
|
parts.resources.push((pattern, Some(resource)));
|
2017-10-15 23:17:41 +02:00
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-12 01:26:51 +01:00
|
|
|
/// Default resource is used if no matched route could be found.
|
2018-04-04 07:06:18 +02:00
|
|
|
pub fn default_resource<F, R>(mut self, f: F) -> App<S>
|
|
|
|
where F: FnOnce(&mut ResourceHandler<S>) -> R + 'static
|
2017-10-15 23:17:41 +02:00
|
|
|
{
|
|
|
|
{
|
|
|
|
let parts = self.parts.as_mut().expect("Use after finish");
|
|
|
|
f(&mut parts.default);
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2018-02-19 07:23:17 +01:00
|
|
|
/// Set default content encoding. `ContentEncoding::Auto` is set by default.
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn default_encoding<F>(mut self, encoding: ContentEncoding) -> App<S>
|
2018-02-19 07:23:17 +01:00
|
|
|
{
|
|
|
|
{
|
|
|
|
let parts = self.parts.as_mut().expect("Use after finish");
|
|
|
|
parts.encoding = encoding;
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-08 01:22:26 +01:00
|
|
|
/// 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;
|
2018-03-31 09:16:55 +02:00
|
|
|
/// use actix_web::{App, HttpRequest, HttpResponse, Result};
|
2017-12-08 01:22:26 +01:00
|
|
|
///
|
|
|
|
/// fn index(mut req: HttpRequest) -> Result<HttpResponse> {
|
|
|
|
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
|
|
|
|
/// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
|
2018-03-31 08:07:33 +02:00
|
|
|
/// Ok(HttpResponse::Ok().into())
|
2017-12-08 01:22:26 +01:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
2018-03-31 09:16:55 +02:00
|
|
|
/// let app = App::new()
|
2017-12-08 01:22:26 +01:00
|
|
|
/// .resource("/index.html", |r| r.f(index))
|
|
|
|
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
|
|
|
|
/// .finish();
|
|
|
|
/// }
|
|
|
|
/// ```
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn external_resource<T, U>(mut self, name: T, url: U) -> App<S>
|
2017-12-08 01:22:26 +01:00
|
|
|
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(
|
2018-04-02 02:37:22 +02:00
|
|
|
String::from(name.as_ref()),
|
|
|
|
Resource::external(name.as_ref(), url.as_ref()));
|
2017-12-08 01:22:26 +01:00
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2018-01-02 22:09:02 +01:00
|
|
|
/// Configure handler for specific path prefix.
|
|
|
|
///
|
|
|
|
/// Path prefix consists valid path segments. i.e for prefix `/app`
|
|
|
|
/// any request with following paths `/app`, `/app/` or `/app/test`
|
|
|
|
/// would match, but path `/application` would not match.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
2018-03-31 09:16:55 +02:00
|
|
|
/// use actix_web::{http, App, HttpRequest, HttpResponse};
|
2018-01-02 22:09:02 +01:00
|
|
|
///
|
|
|
|
/// fn main() {
|
2018-03-31 09:16:55 +02:00
|
|
|
/// let app = App::new()
|
2018-01-02 22:09:02 +01:00
|
|
|
/// .handler("/app", |req: HttpRequest| {
|
|
|
|
/// match *req.method() {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// http::Method::GET => HttpResponse::Ok(),
|
|
|
|
/// http::Method::POST => HttpResponse::MethodNotAllowed(),
|
|
|
|
/// _ => HttpResponse::NotFound(),
|
2018-01-02 22:09:02 +01:00
|
|
|
/// }});
|
|
|
|
/// }
|
|
|
|
/// ```
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn handler<H: Handler<S>>(mut self, path: &str, handler: H) -> App<S>
|
2018-01-02 22:09:02 +01:00
|
|
|
{
|
|
|
|
{
|
|
|
|
let path = path.trim().trim_right_matches('/').to_owned();
|
|
|
|
let parts = self.parts.as_mut().expect("Use after finish");
|
|
|
|
parts.handlers.push((path, Box::new(WrapHandler::new(handler))));
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-04 23:53:40 +01:00
|
|
|
/// Register a middleware
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn middleware<M: Middleware<S>>(mut self, mw: M) -> App<S> {
|
2017-10-22 07:59:09 +02:00
|
|
|
self.parts.as_mut().expect("Use after finish")
|
|
|
|
.middlewares.push(Box::new(mw));
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2018-03-27 20:16:02 +02:00
|
|
|
/// Run external configuration as part of application building process
|
|
|
|
///
|
|
|
|
/// This function is useful for moving part of configuration to a different
|
|
|
|
/// module or event library. For example we can move some of the resources
|
|
|
|
/// configuration to different module.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
2018-03-31 09:16:55 +02:00
|
|
|
/// use actix_web::{App, HttpResponse, http, fs, middleware};
|
2018-03-27 20:16:02 +02:00
|
|
|
///
|
|
|
|
/// // this function could be located in different module
|
2018-03-31 09:16:55 +02:00
|
|
|
/// fn config(app: App) -> App {
|
2018-03-27 20:16:02 +02:00
|
|
|
/// app
|
|
|
|
/// .resource("/test", |r| {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
|
|
|
|
/// r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
|
2018-03-27 20:16:02 +02:00
|
|
|
/// })
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
2018-03-31 09:16:55 +02:00
|
|
|
/// let app = App::new()
|
2018-03-27 20:16:02 +02:00
|
|
|
/// .middleware(middleware::Logger::default())
|
|
|
|
/// .configure(config) // <- register resources
|
|
|
|
/// .handler("/static", fs::StaticFiles::new(".", true));
|
|
|
|
/// }
|
|
|
|
/// ```
|
2018-03-31 09:16:55 +02:00
|
|
|
pub fn configure<F>(self, cfg: F) -> App<S>
|
|
|
|
where F: Fn(App<S>) -> App<S>
|
2018-03-27 20:16:02 +02:00
|
|
|
{
|
|
|
|
cfg(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");
|
2017-12-07 01:26:27 +01:00
|
|
|
let prefix = parts.prefix.trim().trim_right_matches('/');
|
2017-12-08 01:22:26 +01:00
|
|
|
|
|
|
|
let mut resources = parts.resources;
|
|
|
|
for (_, pattern) in parts.external {
|
2018-02-22 14:48:18 +01:00
|
|
|
resources.push((pattern, None));
|
2017-12-08 01:22:26 +01:00
|
|
|
}
|
|
|
|
|
2017-12-29 20:33:04 +01:00
|
|
|
let (router, resources) = Router::new(prefix, parts.settings, resources);
|
2017-12-29 10:01:31 +01:00
|
|
|
|
2018-04-02 19:27:37 +02:00
|
|
|
let inner = Rc::new(UnsafeCell::new(
|
2017-12-29 10:01:31 +01:00
|
|
|
Inner {
|
2018-01-03 00:23:31 +01:00
|
|
|
prefix: prefix.len(),
|
2017-12-29 10:01:31 +01:00
|
|
|
default: parts.default,
|
2018-02-19 07:23:17 +01:00
|
|
|
encoding: parts.encoding,
|
2018-01-02 22:09:02 +01:00
|
|
|
handlers: parts.handlers,
|
2018-02-26 23:33:56 +01:00
|
|
|
resources,
|
2018-01-02 22:09:02 +01:00
|
|
|
}
|
2017-12-29 10:01:31 +01:00
|
|
|
));
|
|
|
|
|
2017-12-06 20:00:39 +01:00
|
|
|
HttpApplication {
|
2017-10-22 03:54:24 +02:00
|
|
|
state: Rc::new(parts.state),
|
2017-12-07 01:26:27 +01:00
|
|
|
prefix: prefix.to_owned(),
|
2017-12-29 10:01:31 +01:00
|
|
|
router: router.clone(),
|
2017-10-22 07:59:09 +02:00
|
|
|
middlewares: Rc::new(parts.middlewares),
|
2018-02-26 23:33:56 +01:00
|
|
|
inner,
|
2017-10-22 07:59:09 +02:00
|
|
|
}
|
2017-10-15 23:17:41 +02:00
|
|
|
}
|
2018-01-14 03:58:17 +01:00
|
|
|
|
|
|
|
/// Convenience method for creating `Box<HttpHandler>` instance.
|
|
|
|
///
|
2018-03-31 09:16:55 +02:00
|
|
|
/// This method is useful if you need to register multiple application instances
|
2018-01-14 03:58:17 +01:00
|
|
|
/// with different state.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::thread;
|
|
|
|
/// # extern crate actix_web;
|
2018-04-06 18:45:10 +02:00
|
|
|
/// use actix_web::{server, App, HttpResponse};
|
2018-01-14 03:58:17 +01:00
|
|
|
///
|
|
|
|
/// struct State1;
|
|
|
|
///
|
|
|
|
/// struct State2;
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// # thread::spawn(|| {
|
2018-04-06 18:45:10 +02:00
|
|
|
/// server::new(|| { vec![
|
2018-03-31 09:16:55 +02:00
|
|
|
/// App::with_state(State1)
|
2018-01-14 03:58:17 +01:00
|
|
|
/// .prefix("/app1")
|
2018-03-31 08:07:33 +02:00
|
|
|
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
|
2018-01-14 03:58:17 +01:00
|
|
|
/// .boxed(),
|
2018-03-31 09:16:55 +02:00
|
|
|
/// App::with_state(State2)
|
2018-01-14 03:58:17 +01:00
|
|
|
/// .prefix("/app2")
|
2018-03-31 08:07:33 +02:00
|
|
|
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
|
2018-01-14 03:58:17 +01:00
|
|
|
/// .boxed() ]})
|
|
|
|
/// .bind("127.0.0.1:8080").unwrap()
|
|
|
|
/// .run()
|
|
|
|
/// # });
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn boxed(mut self) -> Box<HttpHandler> {
|
|
|
|
Box::new(self.finish())
|
|
|
|
}
|
2017-10-15 23:17:41 +02:00
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
impl<S: 'static> IntoHttpHandler for App<S> {
|
2017-12-06 20:00:39 +01:00
|
|
|
type Handler = HttpApplication<S>;
|
|
|
|
|
2017-12-29 20:33:04 +01:00
|
|
|
fn into_handler(mut self, settings: ServerSettings) -> HttpApplication<S> {
|
|
|
|
{
|
|
|
|
let parts = self.parts.as_mut().expect("Use after finish");
|
|
|
|
parts.settings = settings;
|
|
|
|
}
|
2017-12-06 20:00:39 +01:00
|
|
|
self.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
impl<'a, S: 'static> IntoHttpHandler for &'a mut App<S> {
|
2017-12-06 20:00:39 +01:00
|
|
|
type Handler = HttpApplication<S>;
|
|
|
|
|
2017-12-29 20:33:04 +01:00
|
|
|
fn into_handler(self, settings: ServerSettings) -> HttpApplication<S> {
|
|
|
|
{
|
|
|
|
let parts = self.parts.as_mut().expect("Use after finish");
|
|
|
|
parts.settings = settings;
|
|
|
|
}
|
2017-12-06 20:00:39 +01:00
|
|
|
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)]
|
2018-03-31 09:16:55 +02:00
|
|
|
impl<S: 'static> Iterator for App<S> {
|
2017-12-06 20:00:39 +01:00
|
|
|
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 {
|
2018-01-02 22:09:02 +01:00
|
|
|
use http::StatusCode;
|
2017-12-06 22:02:53 +01:00
|
|
|
use super::*;
|
2017-12-27 04:48:02 +01:00
|
|
|
use test::TestRequest;
|
2017-12-06 22:02:53 +01:00
|
|
|
use httprequest::HttpRequest;
|
2018-03-31 08:07:33 +02:00
|
|
|
use httpresponse::HttpResponse;
|
2017-12-06 22:02:53 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_default_resource() {
|
2018-03-31 09:16:55 +02:00
|
|
|
let mut app = App::new()
|
2018-03-31 08:07:33 +02:00
|
|
|
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
|
2017-12-06 22:02:53 +01:00
|
|
|
.finish();
|
|
|
|
|
2017-12-27 04:48:02 +01:00
|
|
|
let req = TestRequest::with_uri("/test").finish();
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
2017-12-06 22:02:53 +01:00
|
|
|
|
2018-01-02 22:09:02 +01:00
|
|
|
let req = TestRequest::with_uri("/blah").finish();
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
|
2017-12-06 22:02:53 +01:00
|
|
|
|
2018-03-31 09:16:55 +02:00
|
|
|
let mut app = App::new()
|
2018-03-31 08:07:33 +02:00
|
|
|
.default_resource(|r| r.f(|_| HttpResponse::MethodNotAllowed()))
|
2017-12-06 22:02:53 +01:00
|
|
|
.finish();
|
2018-01-02 22:09:02 +01:00
|
|
|
let req = TestRequest::with_uri("/blah").finish();
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::METHOD_NOT_ALLOWED);
|
2017-12-06 22:02:53 +01:00
|
|
|
}
|
2017-12-07 03:39:13 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_unhandled_prefix() {
|
2018-03-31 09:16:55 +02:00
|
|
|
let mut app = App::new()
|
2017-12-11 23:16:29 +01:00
|
|
|
.prefix("/test")
|
2018-03-31 08:07:33 +02:00
|
|
|
.resource("/test", |r| r.f(|_| HttpResponse::Ok()))
|
2017-12-07 03:39:13 +01:00
|
|
|
.finish();
|
|
|
|
assert!(app.handle(HttpRequest::default()).is_err());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_state() {
|
2018-03-31 09:16:55 +02:00
|
|
|
let mut app = App::with_state(10)
|
2018-03-31 08:07:33 +02:00
|
|
|
.resource("/", |r| r.f(|_| HttpResponse::Ok()))
|
2017-12-07 03:39:13 +01:00
|
|
|
.finish();
|
2017-12-09 13:33:40 +01:00
|
|
|
let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone());
|
2017-12-09 22:25:06 +01:00
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
2017-12-07 03:39:13 +01:00
|
|
|
}
|
2017-12-29 23:04:13 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_prefix() {
|
2018-03-31 09:16:55 +02:00
|
|
|
let mut app = App::new()
|
2017-12-29 23:04:13 +01:00
|
|
|
.prefix("/test")
|
2018-03-31 08:07:33 +02:00
|
|
|
.resource("/blah", |r| r.f(|_| HttpResponse::Ok()))
|
2017-12-29 23:04:13 +01:00
|
|
|
.finish();
|
|
|
|
let req = TestRequest::with_uri("/test").finish();
|
|
|
|
let resp = app.handle(req);
|
|
|
|
assert!(resp.is_ok());
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/test/").finish();
|
|
|
|
let resp = app.handle(req);
|
|
|
|
assert!(resp.is_ok());
|
|
|
|
|
2018-01-02 22:09:02 +01:00
|
|
|
let req = TestRequest::with_uri("/test/blah").finish();
|
|
|
|
let resp = app.handle(req);
|
|
|
|
assert!(resp.is_ok());
|
|
|
|
|
2017-12-29 23:04:13 +01:00
|
|
|
let req = TestRequest::with_uri("/testing").finish();
|
|
|
|
let resp = app.handle(req);
|
|
|
|
assert!(resp.is_err());
|
|
|
|
}
|
2018-01-02 22:09:02 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_handler() {
|
2018-03-31 09:16:55 +02:00
|
|
|
let mut app = App::new()
|
2018-03-31 08:07:33 +02:00
|
|
|
.handler("/test", |_| HttpResponse::Ok())
|
2018-01-02 22:09:02 +01:00
|
|
|
.finish();
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/test").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/test/").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/test/app").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/testapp").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/blah").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
|
2018-01-03 00:23:31 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_handler_prefix() {
|
2018-03-31 09:16:55 +02:00
|
|
|
let mut app = App::new()
|
2018-01-03 00:23:31 +01:00
|
|
|
.prefix("/app")
|
2018-03-31 08:07:33 +02:00
|
|
|
.handler("/test", |_| HttpResponse::Ok())
|
2018-01-03 00:23:31 +01:00
|
|
|
.finish();
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/test").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/app/test").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/app/test/").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/app/test/app").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/app/testapp").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/app/blah").finish();
|
|
|
|
let resp = app.run(req);
|
|
|
|
assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
|
2018-01-02 22:09:02 +01:00
|
|
|
|
|
|
|
}
|
2018-01-03 00:23:31 +01:00
|
|
|
|
2017-12-06 22:02:53 +01:00
|
|
|
}
|