1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 13:29:24 +00:00
actix-web/src/app.rs

1102 lines
34 KiB
Rust
Raw Normal View History

2019-03-02 06:51:32 +00:00
use std::cell::RefCell;
use std::marker::PhantomData;
use std::rc::Rc;
2019-03-03 00:24:14 +00:00
use actix_http::body::{Body, MessageBody};
2019-03-02 06:51:32 +00:00
use actix_http::{Extensions, PayloadStream, Request, Response};
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
2019-03-02 07:59:44 +00:00
use actix_service::boxed::{self, BoxedNewService, BoxedService};
2019-03-02 06:51:32 +00:00
use actix_service::{
2019-03-05 05:37:57 +00:00
AndThenNewService, ApplyTransform, IntoNewService, IntoTransform, NewService,
Service, Transform,
2019-03-02 06:51:32 +00:00
};
use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, IntoFuture, Poll};
2019-03-04 19:47:53 +00:00
use crate::guard::Guard;
2019-03-02 06:51:32 +00:00
use crate::resource::Resource;
use crate::scope::{insert_slash, Scope};
2019-03-02 06:51:32 +00:00
use crate::service::{ServiceRequest, ServiceResponse};
use crate::state::{State, StateFactory, StateFactoryResult};
2019-03-04 19:47:53 +00:00
type Guards = Vec<Box<Guard>>;
2019-03-02 07:59:44 +00:00
type HttpService<P> = BoxedService<ServiceRequest<P>, ServiceResponse, ()>;
type HttpNewService<P> = BoxedNewService<(), ServiceRequest<P>, ServiceResponse, (), ()>;
2019-03-02 06:51:32 +00:00
type BoxedResponse = Box<Future<Item = ServiceResponse, Error = ()>>;
pub trait HttpServiceFactory<P> {
type Factory: NewService<
ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
>;
2019-03-02 06:51:32 +00:00
fn rdef(&self) -> &ResourceDef;
fn create(self) -> Self::Factory;
}
2019-03-03 06:03:45 +00:00
/// Application builder - structure that follows the builder pattern
/// for building application instances.
2019-03-02 19:53:05 +00:00
pub struct App<P, T>
where
2019-03-05 18:08:08 +00:00
T: NewService<ServiceRequest, Response = ServiceRequest<P>>,
2019-03-02 19:53:05 +00:00
{
chain: T,
2019-03-02 06:51:32 +00:00
extensions: Extensions,
state: Vec<Box<StateFactory>>,
2019-03-02 19:53:05 +00:00
_t: PhantomData<(P,)>,
2019-03-02 06:51:32 +00:00
}
2019-03-02 19:53:05 +00:00
impl App<PayloadStream, AppChain> {
/// Create application builder with empty state. Application can
2019-03-02 06:51:32 +00:00
/// be configured with a builder-like pattern.
pub fn new() -> Self {
2019-03-02 19:53:05 +00:00
App {
chain: AppChain,
extensions: Extensions::new(),
state: Vec::new(),
_t: PhantomData,
}
2019-03-02 06:51:32 +00:00
}
}
2019-03-02 19:53:05 +00:00
impl<P, T> App<P, T>
where
P: 'static,
T: NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest,
2019-03-02 19:53:05 +00:00
Response = ServiceRequest<P>,
Error = (),
InitError = (),
>,
{
2019-03-03 06:03:45 +00:00
/// Set application state. Applicatin state could be accessed
/// by using `State<T>` extractor where `T` is state type.
2019-03-02 06:51:32 +00:00
///
/// **Note**: http server accepts an application factory rather than
/// an application instance. Http server constructs an application
/// instance for each thread, thus application state must be constructed
/// multiple times. If you want to share state between different
/// threads, a shared object should be used, e.g. `Arc`. Application
/// state does not need to be `Send` or `Sync`.
2019-03-03 06:11:24 +00:00
///
/// ```rust
/// use std::cell::Cell;
/// use actix_web::{web, State, App};
///
/// struct MyState {
/// counter: Cell<usize>,
/// }
///
/// fn index(state: State<MyState>) {
/// state.counter.set(state.counter.get() + 1);
/// }
///
/// fn main() {
/// let app = App::new()
/// .state(MyState{ counter: Cell::new(0) })
/// .resource(
/// "/index.html",
/// |r| r.route(web::get().to(index)));
/// }
/// ```
2019-03-02 06:51:32 +00:00
pub fn state<S: 'static>(mut self, state: S) -> Self {
self.state.push(Box::new(State::new(state)));
self
}
2019-03-03 06:03:45 +00:00
/// Set application state factory. This function is
2019-03-02 06:51:32 +00:00
/// similar to `.state()` but it accepts state factory. State get
/// constructed asynchronously during application initialization.
pub fn state_factory<F, Out>(mut self, state: F) -> Self
2019-03-02 06:51:32 +00:00
where
F: Fn() -> Out + 'static,
Out: IntoFuture + 'static,
Out::Error: std::fmt::Debug,
{
self.state.push(Box::new(state));
2019-03-02 06:51:32 +00:00
self
}
2019-03-04 05:02:01 +00:00
/// Configure scope for common root path.
///
/// Scopes collect multiple paths under a common path prefix.
/// Scope path can contain variable path segments as resources.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{App, HttpRequest, HttpResponse};
///
/// fn main() {
/// let app = App::new().scope("/{project_id}", |scope| {
/// scope
/// .resource("/path1", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path2", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path3", |r| r.to(|| HttpResponse::MethodNotAllowed()))
/// });
/// }
/// ```
///
/// In the above example, three routes get added:
/// * /{project_id}/path1
/// * /{project_id}/path2
/// * /{project_id}/path3
///
pub fn scope<F>(self, path: &str, f: F) -> AppRouter<T, P, Body, AppEntry<P>>
where
F: FnOnce(Scope<P>) -> Scope<P>,
{
2019-03-04 19:47:53 +00:00
let mut scope = f(Scope::new(path));
2019-03-04 05:02:01 +00:00
let rdef = scope.rdef().clone();
let default = scope.get_default();
2019-03-04 19:47:53 +00:00
let guards = scope.take_guards();
2019-03-04 05:02:01 +00:00
let fref = Rc::new(RefCell::new(None));
AppRouter {
chain: self.chain,
2019-03-04 19:47:53 +00:00
services: vec![(rdef, boxed::new_service(scope.into_new_service()), guards)],
2019-03-04 05:02:01 +00:00
default: None,
defaults: vec![default],
endpoint: AppEntry::new(fref.clone()),
factory_ref: fref,
extensions: self.extensions,
state: self.state,
_t: PhantomData,
}
}
2019-03-02 19:53:05 +00:00
/// Configure resource for a specific path.
///
/// Resources may have variable path segments. For example, a
/// resource with the path `/a/{name}/c` would match all incoming
/// requests with paths such as `/a/b/c`, `/a/1/c`, or `/a/etc/c`.
///
/// A variable segment is specified in the form `{identifier}`,
/// where the identifier can be used later in a request handler to
/// access the matched value for that segment. This is done by
/// looking up the identifier in the `Params` object returned by
/// `HttpRequest.match_info()` method.
///
/// By default, each segment 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:
///
2019-03-03 06:03:45 +00:00
/// ```rust
2019-03-02 19:53:05 +00:00
/// # extern crate actix_web;
2019-03-03 06:03:45 +00:00
/// use actix_web::{web, http, App, HttpResponse};
2019-03-02 19:53:05 +00:00
///
/// fn main() {
/// let app = App::new().resource("/users/{userid}/{friend}", |r| {
2019-03-03 06:03:45 +00:00
/// r.route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
2019-03-02 19:53:05 +00:00
/// });
/// }
/// ```
2019-03-03 00:24:14 +00:00
pub fn resource<F, U>(self, path: &str, f: F) -> AppRouter<T, P, Body, AppEntry<P>>
2019-03-02 19:53:05 +00:00
where
F: FnOnce(Resource<P>) -> Resource<P, U>,
U: NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
2019-03-02 19:53:05 +00:00
Response = ServiceResponse,
Error = (),
InitError = (),
> + 'static,
{
let rdef = ResourceDef::new(&insert_slash(path));
2019-03-04 19:47:53 +00:00
let res = f(Resource::new());
let default = res.get_default();
2019-03-02 19:53:05 +00:00
2019-03-02 06:51:32 +00:00
let fref = Rc::new(RefCell::new(None));
2019-03-02 19:53:05 +00:00
AppRouter {
chain: self.chain,
2019-03-04 19:47:53 +00:00
services: vec![(rdef, boxed::new_service(res.into_new_service()), None)],
2019-03-02 19:53:05 +00:00
default: None,
defaults: vec![default],
endpoint: AppEntry::new(fref.clone()),
factory_ref: fref,
extensions: self.extensions,
state: self.state,
_t: PhantomData,
}
}
/// Register a middleware.
pub fn middleware<M, B, F>(
2019-03-02 19:53:05 +00:00
self,
mw: F,
) -> AppRouter<
T,
P,
B,
2019-03-02 19:53:05 +00:00
impl NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
Response = ServiceResponse<B>,
2019-03-02 19:53:05 +00:00
Error = (),
InitError = (),
>,
>
where
2019-03-05 05:37:57 +00:00
M: Transform<
2019-03-03 16:24:09 +00:00
AppRouting<P>,
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
Response = ServiceResponse<B>,
2019-03-02 19:53:05 +00:00
Error = (),
InitError = (),
>,
2019-03-05 18:08:08 +00:00
F: IntoTransform<M, AppRouting<P>, ServiceRequest<P>>,
2019-03-02 19:53:05 +00:00
{
let fref = Rc::new(RefCell::new(None));
2019-03-05 05:37:57 +00:00
let endpoint = ApplyTransform::new(mw, AppEntry::new(fref.clone()));
2019-03-02 19:53:05 +00:00
AppRouter {
endpoint,
chain: self.chain,
state: self.state,
services: Vec::new(),
default: None,
defaults: Vec::new(),
factory_ref: fref,
extensions: self.extensions,
_t: PhantomData,
}
}
/// Register a request modifier. It can modify any request parameters
/// including payload stream.
pub fn chain<C, F, P1>(
self,
chain: C,
) -> App<
P1,
impl NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest,
2019-03-02 19:53:05 +00:00
Response = ServiceRequest<P1>,
Error = (),
InitError = (),
>,
>
where
C: NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
2019-03-02 19:53:05 +00:00
Response = ServiceRequest<P1>,
Error = (),
InitError = (),
>,
2019-03-05 18:08:08 +00:00
F: IntoNewService<C, ServiceRequest<P>>,
2019-03-02 19:53:05 +00:00
{
let chain = self.chain.and_then(chain.into_new_service());
2019-03-02 06:51:32 +00:00
App {
2019-03-02 19:53:05 +00:00
chain,
state: self.state,
extensions: self.extensions,
_t: PhantomData,
}
}
2019-03-04 05:02:01 +00:00
/// Register resource handler service.
pub fn service<F>(self, service: F) -> AppRouter<T, P, Body, AppEntry<P>>
where
F: HttpServiceFactory<P> + 'static,
{
let fref = Rc::new(RefCell::new(None));
AppRouter {
chain: self.chain,
services: vec![(
service.rdef().clone(),
boxed::new_service(service.create().map_init_err(|_| ())),
None,
)],
default: None,
defaults: vec![],
endpoint: AppEntry::new(fref.clone()),
factory_ref: fref,
extensions: self.extensions,
state: self.state,
_t: PhantomData,
}
}
2019-03-04 05:02:01 +00:00
/// Set server host name.
///
/// Host name is used by application router aa a hostname for url
/// generation. Check [ConnectionInfo](./dev/struct.ConnectionInfo.
/// html#method.host) documentation for more information.
///
/// By default host name is set to a "localhost" value.
pub fn hostname(self, _val: &str) -> Self {
// self.host = val.to_owned();
self
}
2019-03-02 06:51:32 +00:00
}
2019-03-03 22:45:56 +00:00
/// Application router builder - Structure that follows the builder pattern
/// for building application instances.
2019-03-02 19:53:05 +00:00
pub struct AppRouter<C, P, B, T> {
chain: C,
2019-03-04 19:47:53 +00:00
services: Vec<(ResourceDef, HttpNewService<P>, Option<Guards>)>,
2019-03-02 19:53:05 +00:00
default: Option<Rc<HttpNewService<P>>>,
defaults: Vec<Rc<RefCell<Option<Rc<HttpNewService<P>>>>>>,
endpoint: T,
2019-03-03 16:24:09 +00:00
factory_ref: Rc<RefCell<Option<AppRoutingFactory<P>>>>,
2019-03-02 19:53:05 +00:00
extensions: Extensions,
state: Vec<Box<StateFactory>>,
_t: PhantomData<(P, B)>,
}
impl<C, P, B, T> AppRouter<C, P, B, T>
2019-03-02 06:51:32 +00:00
where
P: 'static,
B: MessageBody,
T: NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
2019-03-02 06:51:32 +00:00
Response = ServiceResponse<B>,
Error = (),
InitError = (),
>,
{
2019-03-04 05:02:01 +00:00
/// Configure scope for common root path.
///
/// Scopes collect multiple paths under a common path prefix.
/// Scope path can contain variable path segments as resources.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{App, HttpRequest, HttpResponse};
///
/// fn main() {
/// let app = App::new().scope("/{project_id}", |scope| {
/// scope
/// .resource("/path1", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path2", |r| r.to(|| HttpResponse::Ok()))
/// .resource("/path3", |r| r.to(|| HttpResponse::MethodNotAllowed()))
/// });
/// }
/// ```
///
/// In the above example, three routes get added:
/// * /{project_id}/path1
/// * /{project_id}/path2
/// * /{project_id}/path3
///
pub fn scope<F>(mut self, path: &str, f: F) -> Self
where
F: FnOnce(Scope<P>) -> Scope<P>,
{
2019-03-04 19:47:53 +00:00
let mut scope = f(Scope::new(path));
2019-03-04 05:02:01 +00:00
let rdef = scope.rdef().clone();
2019-03-04 19:47:53 +00:00
let guards = scope.take_guards();
2019-03-04 05:02:01 +00:00
self.defaults.push(scope.get_default());
self.services
2019-03-04 19:47:53 +00:00
.push((rdef, boxed::new_service(scope.into_new_service()), guards));
2019-03-04 05:02:01 +00:00
self
}
2019-03-02 06:51:32 +00:00
/// Configure resource for a specific path.
///
/// Resources may have variable path segments. For example, a
/// resource with the path `/a/{name}/c` would match all incoming
/// requests with paths such as `/a/b/c`, `/a/1/c`, or `/a/etc/c`.
///
/// A variable segment is specified in the form `{identifier}`,
/// where the identifier can be used later in a request handler to
/// access the matched value for that segment. This is done by
/// looking up the identifier in the `Params` object returned by
/// `HttpRequest.match_info()` method.
///
/// By default, each segment 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:
///
2019-03-03 06:03:45 +00:00
/// ```rust
/// use actix_web::{web, http, App, HttpResponse};
2019-03-02 06:51:32 +00:00
///
/// fn main() {
2019-03-03 06:03:45 +00:00
/// let app = App::new()
/// .resource("/users/{userid}/{friend}", |r| {
/// r.route(web::to(|| HttpResponse::Ok()))
/// })
/// .resource("/index.html", |r| {
/// r.route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// });
2019-03-02 06:51:32 +00:00
/// }
/// ```
pub fn resource<F, U>(mut self, path: &str, f: F) -> Self
where
F: FnOnce(Resource<P>) -> Resource<P, U>,
U: NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
2019-03-02 06:51:32 +00:00
Response = ServiceResponse,
Error = (),
InitError = (),
> + 'static,
{
let rdef = ResourceDef::new(&insert_slash(path));
2019-03-02 06:51:32 +00:00
let resource = f(Resource::new());
self.defaults.push(resource.get_default());
2019-03-04 19:47:53 +00:00
self.services.push((
rdef,
boxed::new_service(resource.into_new_service()),
None,
));
2019-03-02 06:51:32 +00:00
self
}
/// Default resource to be used if no matching route could be found.
///
/// Default resource works with resources only and does not work with
/// custom services.
2019-03-06 03:30:44 +00:00
pub fn default_resource<F, U>(mut self, f: F) -> Self
2019-03-02 06:51:32 +00:00
where
2019-03-06 03:30:44 +00:00
F: FnOnce(Resource<P>) -> Resource<P, U>,
U: NewService<
ServiceRequest<P>,
Response = ServiceResponse,
Error = (),
InitError = (),
> + 'static,
2019-03-02 06:51:32 +00:00
{
// create and configure default resource
2019-03-02 07:59:44 +00:00
self.default = Some(Rc::new(boxed::new_service(
f(Resource::new()).into_new_service().map_init_err(|_| ()),
)));
2019-03-02 06:51:32 +00:00
self
}
/// Register resource handler service.
pub fn service<F>(mut self, factory: F) -> Self
2019-03-02 06:51:32 +00:00
where
F: HttpServiceFactory<P> + 'static,
2019-03-02 06:51:32 +00:00
{
let rdef = factory.rdef().clone();
2019-03-02 06:51:32 +00:00
self.services.push((
rdef,
boxed::new_service(factory.create().map_init_err(|_| ())),
2019-03-04 19:47:53 +00:00
None,
2019-03-02 06:51:32 +00:00
));
self
}
/// Register a middleware.
pub fn middleware<M, B1, F>(
self,
mw: F,
2019-03-02 19:53:05 +00:00
) -> AppRouter<
C,
2019-03-02 06:51:32 +00:00
P,
B1,
impl NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
2019-03-02 06:51:32 +00:00
Response = ServiceResponse<B1>,
Error = (),
InitError = (),
>,
>
where
2019-03-05 05:37:57 +00:00
M: Transform<
2019-03-02 06:51:32 +00:00
T::Service,
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
2019-03-02 06:51:32 +00:00
Response = ServiceResponse<B1>,
Error = (),
InitError = (),
>,
B1: MessageBody,
2019-03-05 18:08:08 +00:00
F: IntoTransform<M, T::Service, ServiceRequest<P>>,
2019-03-02 06:51:32 +00:00
{
2019-03-05 05:37:57 +00:00
let endpoint = ApplyTransform::new(mw, self.endpoint);
2019-03-02 19:53:05 +00:00
AppRouter {
2019-03-02 06:51:32 +00:00
endpoint,
2019-03-02 19:53:05 +00:00
chain: self.chain,
2019-03-02 06:51:32 +00:00
state: self.state,
services: self.services,
default: self.default,
2019-03-02 19:53:05 +00:00
defaults: self.defaults,
2019-03-02 06:51:32 +00:00
factory_ref: self.factory_ref,
2019-03-02 19:53:05 +00:00
extensions: self.extensions,
2019-03-02 06:51:32 +00:00
_t: PhantomData,
}
}
/// Register an external resource.
///
/// External resources are useful for URL generation purposes only
/// and are never considered for matching at request time. Calls to
/// `HttpRequest::url_for()` will work as expected.
///
/// ```rust,ignore
/// # extern crate actix_web;
/// use actix_web::{App, HttpRequest, HttpResponse, Result};
///
/// fn index(req: &HttpRequest) -> Result<HttpResponse> {
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
/// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
/// Ok(HttpResponse::Ok().into())
/// }
///
/// fn main() {
/// let app = App::new()
/// .resource("/index.html", |r| r.get().f(index))
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
/// .finish();
/// }
/// ```
pub fn external_resource<N, U>(self, _name: N, _url: U) -> Self
where
N: AsRef<str>,
U: AsRef<str>,
{
// self.parts
// .as_mut()
// .expect("Use after finish")
// .router
// .register_external(name.as_ref(), ResourceDef::external(url.as_ref()));
self
}
}
2019-03-02 19:53:05 +00:00
impl<C, T, P: 'static, B: MessageBody>
2019-03-05 18:08:08 +00:00
IntoNewService<AndThenNewService<AppInit<C, P>, T>, Request>
for AppRouter<C, P, B, T>
2019-03-02 06:51:32 +00:00
where
T: NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest<P>,
2019-03-02 06:51:32 +00:00
Response = ServiceResponse<B>,
Error = (),
InitError = (),
>,
2019-03-02 19:53:05 +00:00
C: NewService<
2019-03-05 18:08:08 +00:00
ServiceRequest,
2019-03-02 19:53:05 +00:00
Response = ServiceRequest<P>,
Error = (),
InitError = (),
>,
2019-03-02 06:51:32 +00:00
{
2019-03-05 18:08:08 +00:00
fn into_new_service(self) -> AndThenNewService<AppInit<C, P>, T> {
2019-03-02 06:51:32 +00:00
// update resource default service
if self.default.is_some() {
for default in &self.defaults {
if default.borrow_mut().is_none() {
*default.borrow_mut() = self.default.clone();
}
}
}
// set factory
2019-03-03 16:24:09 +00:00
*self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
2019-03-04 05:02:01 +00:00
default: self.default.clone(),
2019-03-04 19:47:53 +00:00
services: Rc::new(
self.services
.into_iter()
.map(|(rdef, srv, guards)| (rdef, srv, RefCell::new(guards)))
.collect(),
),
2019-03-02 06:51:32 +00:00
});
2019-03-02 19:53:05 +00:00
AppInit {
chain: self.chain,
2019-03-02 06:51:32 +00:00
state: self.state,
extensions: Rc::new(RefCell::new(Rc::new(self.extensions))),
}
.and_then(self.endpoint)
}
}
2019-03-03 16:24:09 +00:00
pub struct AppRoutingFactory<P> {
2019-03-04 19:47:53 +00:00
services: Rc<Vec<(ResourceDef, HttpNewService<P>, RefCell<Option<Guards>>)>>,
2019-03-04 05:02:01 +00:00
default: Option<Rc<HttpNewService<P>>>,
2019-03-02 06:51:32 +00:00
}
2019-03-05 18:08:08 +00:00
impl<P: 'static> NewService<ServiceRequest<P>> for AppRoutingFactory<P> {
2019-03-02 06:51:32 +00:00
type Response = ServiceResponse;
type Error = ();
type InitError = ();
2019-03-03 16:24:09 +00:00
type Service = AppRouting<P>;
type Future = AppRoutingFactoryResponse<P>;
2019-03-02 06:51:32 +00:00
fn new_service(&self, _: &()) -> Self::Future {
2019-03-04 05:02:01 +00:00
let default_fut = if let Some(ref default) = self.default {
Some(default.new_service(&()))
} else {
None
};
2019-03-03 16:24:09 +00:00
AppRoutingFactoryResponse {
2019-03-02 06:51:32 +00:00
fut: self
.services
.iter()
2019-03-04 19:47:53 +00:00
.map(|(path, service, guards)| {
2019-03-03 16:24:09 +00:00
CreateAppRoutingItem::Future(
2019-03-02 06:51:32 +00:00
Some(path.clone()),
2019-03-04 19:47:53 +00:00
guards.borrow_mut().take(),
2019-03-02 06:51:32 +00:00
service.new_service(&()),
)
})
.collect(),
2019-03-04 05:02:01 +00:00
default: None,
default_fut,
2019-03-02 06:51:32 +00:00
}
}
}
2019-03-02 07:59:44 +00:00
type HttpServiceFut<P> = Box<Future<Item = HttpService<P>, Error = ()>>;
2019-03-02 06:51:32 +00:00
/// Create app service
#[doc(hidden)]
2019-03-03 16:24:09 +00:00
pub struct AppRoutingFactoryResponse<P> {
fut: Vec<CreateAppRoutingItem<P>>,
2019-03-04 05:02:01 +00:00
default: Option<HttpService<P>>,
default_fut: Option<Box<Future<Item = HttpService<P>, Error = ()>>>,
2019-03-02 06:51:32 +00:00
}
2019-03-03 16:24:09 +00:00
enum CreateAppRoutingItem<P> {
2019-03-04 19:47:53 +00:00
Future(Option<ResourceDef>, Option<Guards>, HttpServiceFut<P>),
Service(ResourceDef, Option<Guards>, HttpService<P>),
2019-03-02 06:51:32 +00:00
}
2019-03-03 16:24:09 +00:00
impl<P> Future for AppRoutingFactoryResponse<P> {
type Item = AppRouting<P>;
2019-03-02 06:51:32 +00:00
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut done = true;
2019-03-04 05:02:01 +00:00
if let Some(ref mut fut) = self.default_fut {
match fut.poll()? {
Async::Ready(default) => self.default = Some(default),
Async::NotReady => done = false,
}
}
2019-03-02 06:51:32 +00:00
// poll http services
for item in &mut self.fut {
let res = match item {
2019-03-04 19:47:53 +00:00
CreateAppRoutingItem::Future(
ref mut path,
ref mut guards,
ref mut fut,
) => match fut.poll()? {
Async::Ready(service) => {
Some((path.take().unwrap(), guards.take(), service))
2019-03-02 06:51:32 +00:00
}
2019-03-04 19:47:53 +00:00
Async::NotReady => {
done = false;
None
}
},
CreateAppRoutingItem::Service(_, _, _) => continue,
2019-03-02 06:51:32 +00:00
};
2019-03-04 19:47:53 +00:00
if let Some((path, guards, service)) = res {
*item = CreateAppRoutingItem::Service(path, guards, service);
2019-03-02 06:51:32 +00:00
}
}
if done {
let router = self
.fut
.drain(..)
.fold(Router::build(), |mut router, item| {
match item {
2019-03-04 19:47:53 +00:00
CreateAppRoutingItem::Service(path, guards, service) => {
router.rdef(path, service);
router.set_user_data(guards);
2019-03-02 06:51:32 +00:00
}
2019-03-04 19:47:53 +00:00
CreateAppRoutingItem::Future(_, _, _) => unreachable!(),
2019-03-02 06:51:32 +00:00
}
router
});
2019-03-03 16:24:09 +00:00
Ok(Async::Ready(AppRouting {
2019-03-02 06:51:32 +00:00
ready: None,
2019-03-04 05:02:01 +00:00
router: router.finish(),
default: self.default.take(),
2019-03-02 06:51:32 +00:00
}))
} else {
Ok(Async::NotReady)
}
}
}
2019-03-03 16:24:09 +00:00
pub struct AppRouting<P> {
2019-03-04 19:47:53 +00:00
router: Router<HttpService<P>, Guards>,
2019-03-02 06:51:32 +00:00
ready: Option<(ServiceRequest<P>, ResourceInfo)>,
2019-03-04 05:02:01 +00:00
default: Option<HttpService<P>>,
2019-03-02 06:51:32 +00:00
}
2019-03-05 18:08:08 +00:00
impl<P> Service<ServiceRequest<P>> for AppRouting<P> {
2019-03-02 06:51:32 +00:00
type Response = ServiceResponse;
type Error = ();
type Future = Either<BoxedResponse, FutureResult<Self::Response, Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
if self.ready.is_none() {
Ok(Async::Ready(()))
} else {
Ok(Async::NotReady)
}
}
fn call(&mut self, mut req: ServiceRequest<P>) -> Self::Future {
2019-03-04 19:47:53 +00:00
let res = self.router.recognize_mut_checked(&mut req, |req, guards| {
if let Some(ref guards) = guards {
for f in guards {
if !f.check(req.head()) {
return false;
}
}
}
true
});
if let Some((srv, _info)) = res {
2019-03-02 06:51:32 +00:00
Either::A(srv.call(req))
2019-03-04 05:02:01 +00:00
} else if let Some(ref mut default) = self.default {
Either::A(default.call(req))
2019-03-02 06:51:32 +00:00
} else {
let req = req.into_request();
Either::B(ok(ServiceResponse::new(req, Response::NotFound().finish())))
}
}
}
#[doc(hidden)]
2019-03-03 16:24:09 +00:00
/// Wrapper service for routing
2019-03-02 06:51:32 +00:00
pub struct AppEntry<P> {
2019-03-03 16:24:09 +00:00
factory: Rc<RefCell<Option<AppRoutingFactory<P>>>>,
2019-03-02 06:51:32 +00:00
}
impl<P> AppEntry<P> {
2019-03-03 16:24:09 +00:00
fn new(factory: Rc<RefCell<Option<AppRoutingFactory<P>>>>) -> Self {
2019-03-02 06:51:32 +00:00
AppEntry { factory }
}
}
2019-03-05 18:08:08 +00:00
impl<P: 'static> NewService<ServiceRequest<P>> for AppEntry<P> {
2019-03-02 06:51:32 +00:00
type Response = ServiceResponse;
type Error = ();
type InitError = ();
2019-03-03 16:24:09 +00:00
type Service = AppRouting<P>;
type Future = AppRoutingFactoryResponse<P>;
2019-03-02 06:51:32 +00:00
fn new_service(&self, _: &()) -> Self::Future {
self.factory.borrow_mut().as_mut().unwrap().new_service(&())
}
}
2019-03-02 19:53:05 +00:00
#[doc(hidden)]
pub struct AppChain;
2019-03-05 18:08:08 +00:00
impl NewService<ServiceRequest> for AppChain {
type Response = ServiceRequest;
2019-03-02 19:53:05 +00:00
type Error = ();
type InitError = ();
type Service = AppChain;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &()) -> Self::Future {
ok(AppChain)
}
}
2019-03-05 18:08:08 +00:00
impl Service<ServiceRequest> for AppChain {
type Response = ServiceRequest;
2019-03-02 19:53:05 +00:00
type Error = ();
type Future = FutureResult<Self::Response, Self::Error>;
2019-03-03 16:24:09 +00:00
#[inline]
2019-03-02 19:53:05 +00:00
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
2019-03-03 16:24:09 +00:00
#[inline]
2019-03-05 18:08:08 +00:00
fn call(&mut self, req: ServiceRequest) -> Self::Future {
2019-03-02 19:53:05 +00:00
ok(req)
}
}
2019-03-03 16:24:09 +00:00
/// Service factory to convert `Request` to a `ServiceRequest<S>`.
/// It also executes state factories.
2019-03-02 19:53:05 +00:00
pub struct AppInit<C, P>
where
2019-03-05 18:08:08 +00:00
C: NewService<ServiceRequest, Response = ServiceRequest<P>>,
2019-03-02 19:53:05 +00:00
{
chain: C,
state: Vec<Box<StateFactory>>,
extensions: Rc<RefCell<Rc<Extensions>>>,
}
2019-03-05 18:08:08 +00:00
impl<C, P: 'static> NewService<Request> for AppInit<C, P>
2019-03-02 19:53:05 +00:00
where
2019-03-05 18:08:08 +00:00
C: NewService<ServiceRequest, Response = ServiceRequest<P>, InitError = ()>,
2019-03-02 19:53:05 +00:00
{
type Response = ServiceRequest<P>;
type Error = C::Error;
type InitError = C::InitError;
type Service = AppInitService<C::Service, P>;
type Future = AppInitResult<C, P>;
fn new_service(&self, _: &()) -> Self::Future {
AppInitResult {
chain: self.chain.new_service(&()),
state: self.state.iter().map(|s| s.construct()).collect(),
extensions: self.extensions.clone(),
}
}
}
#[doc(hidden)]
pub struct AppInitResult<C, P>
where
2019-03-05 18:08:08 +00:00
C: NewService<ServiceRequest, Response = ServiceRequest<P>, InitError = ()>,
2019-03-02 19:53:05 +00:00
{
chain: C::Future,
state: Vec<Box<StateFactoryResult>>,
extensions: Rc<RefCell<Rc<Extensions>>>,
}
impl<C, P> Future for AppInitResult<C, P>
where
2019-03-05 18:08:08 +00:00
C: NewService<ServiceRequest, Response = ServiceRequest<P>, InitError = ()>,
2019-03-02 19:53:05 +00:00
{
type Item = AppInitService<C::Service, P>;
type Error = C::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(extensions) = Rc::get_mut(&mut *self.extensions.borrow_mut()) {
let mut idx = 0;
while idx < self.state.len() {
if let Async::Ready(_) = self.state[idx].poll_result(extensions)? {
self.state.remove(idx);
} else {
idx += 1;
}
}
if !self.state.is_empty() {
return Ok(Async::NotReady);
}
} else {
log::warn!("Multiple copies of app extensions exists");
}
let chain = futures::try_ready!(self.chain.poll());
Ok(Async::Ready(AppInitService {
chain,
extensions: self.extensions.borrow().clone(),
}))
}
}
/// Service to convert `Request` to a `ServiceRequest<S>`
pub struct AppInitService<C, P>
where
2019-03-05 18:08:08 +00:00
C: Service<ServiceRequest, Response = ServiceRequest<P>>,
2019-03-02 19:53:05 +00:00
{
chain: C,
extensions: Rc<Extensions>,
}
2019-03-05 18:08:08 +00:00
impl<C, P> Service<Request> for AppInitService<C, P>
2019-03-02 19:53:05 +00:00
where
2019-03-05 18:08:08 +00:00
C: Service<ServiceRequest, Response = ServiceRequest<P>>,
2019-03-02 19:53:05 +00:00
{
type Response = ServiceRequest<P>;
type Error = C::Error;
type Future = C::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.chain.poll_ready()
}
2019-03-05 18:08:08 +00:00
fn call(&mut self, req: Request) -> Self::Future {
2019-03-02 19:53:05 +00:00
let req = ServiceRequest::new(
Path::new(Url::new(req.uri().clone())),
req,
self.extensions.clone(),
);
self.chain.call(req)
}
}
#[cfg(test)]
mod tests {
use actix_http::http::{Method, StatusCode};
use super::*;
2019-03-06 03:03:59 +00:00
use crate::test::{self, block_on, TestRequest};
use crate::{web, HttpResponse, State};
#[test]
fn test_default_resource() {
2019-03-06 03:03:59 +00:00
let mut srv = test::init_service(
App::new().resource("/test", |r| r.to(|| HttpResponse::Ok())),
);
let req = TestRequest::with_uri("/test").to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/blah").to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
2019-03-06 03:03:59 +00:00
let mut srv = test::init_service(
App::new()
.resource("/test", |r| r.to(|| HttpResponse::Ok()))
.resource("/test2", |r| {
r.default_resource(|r| r.to(|| HttpResponse::Created()))
.route(web::get().to(|| HttpResponse::Ok()))
})
.default_resource(|r| r.to(|| HttpResponse::MethodNotAllowed())),
);
let req = TestRequest::with_uri("/blah").to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let req = TestRequest::with_uri("/test2").to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/test2")
.method(Method::POST)
.to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[test]
fn test_state() {
2019-03-06 03:03:59 +00:00
let mut srv = test::init_service(
App::new()
.state(10usize)
.resource("/", |r| r.to(|_: State<usize>| HttpResponse::Ok())),
);
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
2019-03-06 03:03:59 +00:00
let mut srv = test::init_service(
App::new()
.state(10u32)
.resource("/", |r| r.to(|_: State<usize>| HttpResponse::Ok())),
);
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn test_state_factory() {
2019-03-06 03:03:59 +00:00
let mut srv = test::init_service(
App::new()
.state_factory(|| Ok::<_, ()>(10usize))
.resource("/", |r| r.to(|_: State<usize>| HttpResponse::Ok())),
);
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
2019-03-06 03:03:59 +00:00
let mut srv = test::init_service(
App::new()
.state_factory(|| Ok::<_, ()>(10u32))
.resource("/", |r| r.to(|_: State<usize>| HttpResponse::Ok())),
);
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
// #[test]
// fn test_handler() {
// let app = App::new()
// .handler("/test", |_: &_| HttpResponse::Ok())
// .finish();
// let req = TestRequest::with_uri("/test").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// let req = TestRequest::with_uri("/test/").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// let req = TestRequest::with_uri("/test/app").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// let req = TestRequest::with_uri("/testapp").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
// let req = TestRequest::with_uri("/blah").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
// }
// #[test]
// fn test_handler2() {
// let app = App::new()
// .handler("test", |_: &_| HttpResponse::Ok())
// .finish();
// let req = TestRequest::with_uri("/test").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// let req = TestRequest::with_uri("/test/").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// let req = TestRequest::with_uri("/test/app").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// let req = TestRequest::with_uri("/testapp").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
// let req = TestRequest::with_uri("/blah").request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
// }
// #[test]
// fn test_route() {
// let app = App::new()
// .route("/test", Method::GET, |_: HttpRequest| HttpResponse::Ok())
// .route("/test", Method::POST, |_: HttpRequest| {
// HttpResponse::Created()
// })
// .finish();
// let req = TestRequest::with_uri("/test").method(Method::GET).request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::OK);
// let req = TestRequest::with_uri("/test")
// .method(Method::POST)
// .request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::CREATED);
// let req = TestRequest::with_uri("/test")
// .method(Method::HEAD)
// .request();
// let resp = app.run(req);
// assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
// }
}