use std::cell::RefCell; use std::marker::PhantomData; use std::rc::Rc; use actix_http::body::{Body, MessageBody}; use actix_server_config::ServerConfig; use actix_service::boxed::{self, BoxedNewService}; use actix_service::{ ApplyTransform, IntoNewService, IntoTransform, NewService, Transform, }; use futures::IntoFuture; use crate::app_service::{AppChain, AppEntry, AppInit, AppRouting, AppRoutingFactory}; use crate::config::{AppConfig, AppConfigInner}; use crate::data::{Data, DataFactory}; use crate::dev::{PayloadStream, ResourceDef}; use crate::error::Error; use crate::resource::Resource; use crate::route::Route; use crate::service::{ HttpServiceFactory, ServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse, }; type HttpNewService
= BoxedNewService<(), ServiceRequest
, ServiceResponse, Error, ()>; /// Application builder - structure that follows the builder pattern /// for building application instances. pub struct App
where
T: NewService App
where
P: 'static,
T: NewService<
Request = ServiceRequest,
Response = ServiceRequest ,
Error = Error,
InitError = (),
>,
{
/// Set application data. Applicatin data could be accessed
/// by using `Data ,
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
>
where
M: Transform<
AppRouting ,
Request = ServiceRequest ,
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
F: IntoTransform ,
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
>
where
F: FnMut(ServiceRequest , &mut AppRouting ) -> R + Clone,
R: IntoFuture ,
Response = ServiceRequest ,
) -> AppRouter + 'static,
{
let fref = Rc::new(RefCell::new(None));
AppRouter {
chain: self.chain,
default: None,
endpoint: AppEntry::new(fref.clone()),
factory_ref: fref,
data: self.data,
config: self.config,
services: vec![Box::new(ServiceFactoryWrapper::new(service))],
external: Vec::new(),
_t: PhantomData,
}
}
/// Set server host name.
///
/// Host name is used by application router as 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(mut self, val: &str) -> Self {
self.config.host = val.to_owned();
self
}
}
/// Application router builder - Structure that follows the builder pattern
/// for building application instances.
pub struct AppRouter ,
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
{
/// Configure route for a specific path.
///
/// This is a simplified version of the `App::service()` method.
/// This method can not be could multiple times, in that case
/// multiple resources with one route would be registered for same resource path.
///
/// ```rust
/// use actix_web::{web, App, HttpResponse};
///
/// fn index(data: web::Path<(String, String)>) -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new()
/// .route("/test1", web::get().to(index))
/// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()));
/// }
/// ```
pub fn route(self, path: &str, mut route: Route ) -> Self {
self.service(
Resource::new(path)
.add_guards(route.take_guards())
.route(route),
)
}
/// Register http service.
///
/// Http service is any type that implements `HttpServiceFactory` trait.
///
/// Actix web provides several services implementations:
///
/// * *Resource* is an entry in resource table which corresponds to requested URL.
/// * *Scope* is a set of resources with common root path.
/// * "StaticFiles" is a service for static files support
pub fn service + 'static,
{
self.services
.push(Box::new(ServiceFactoryWrapper::new(factory)));
self
}
/// Register a middleware.
pub fn wrap ,
Response = ServiceResponse ,
Response = ServiceResponse ,
Response = ServiceResponse , &mut T::Service) -> R + Clone,
R: IntoFuture ) -> Resource ,
U: NewService<
Request = ServiceRequest ,
Response = ServiceResponse,
Error = Error,
InitError = (),
> + 'static,
{
// create and configure default resource
self.default = Some(Rc::new(boxed::new_service(
f(Resource::new("")).into_new_service().map_init_err(|_| ()),
)));
self
}
/// 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
/// use actix_web::{web, App, HttpRequest, HttpResponse, Result};
///
/// fn index(req: HttpRequest) -> Result ,
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
C: NewService<
Request = ServiceRequest,
Response = ServiceRequest ,
Error = Error,
InitError = (),
>,
{
fn into_new_service(self) -> AppInit ,
srv: &mut S,
) -> impl IntoFuture ,
Response = ServiceResponse,
Error = Error,
>,
{
srv.call(req).map(|mut res| {
res.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
res
})
}
#[test]
fn test_wrap() {
let mut srv = init_service(
App::new()
.wrap(md)
.route("/test", web::get().to(|| HttpResponse::Ok())),
);
let req = TestRequest::with_uri("/test").to_request();
let resp = call_success(&mut srv, req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
#[test]
fn test_router_wrap() {
let mut srv = init_service(
App::new()
.route("/test", web::get().to(|| HttpResponse::Ok()))
.wrap(md),
);
let req = TestRequest::with_uri("/test").to_request();
let resp = call_success(&mut srv, req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
#[test]
fn test_wrap_fn() {
let mut srv = init_service(
App::new()
.wrap_fn(|req, srv| {
srv.call(req).map(|mut res| {
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("0001"),
);
res
})
})
.service(web::resource("/test").to(|| HttpResponse::Ok())),
);
let req = TestRequest::with_uri("/test").to_request();
let resp = call_success(&mut srv, req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
#[test]
fn test_router_wrap_fn() {
let mut srv = init_service(
App::new()
.route("/test", web::get().to(|| HttpResponse::Ok()))
.wrap_fn(|req, srv| {
srv.call(req).map(|mut res| {
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("0001"),
);
res
})
}),
);
let req = TestRequest::with_uri("/test").to_request();
let resp = call_success(&mut srv, req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
}
(
req: ServiceRequest