1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-10 19:01:05 +00:00
actix-web/src/app.rs

688 lines
23 KiB
Rust
Raw Normal View History

2019-03-02 06:51:32 +00:00
use std::cell::RefCell;
use std::fmt;
2019-11-20 17:33:22 +00:00
use std::future::Future;
2019-03-02 06:51:32 +00:00
use std::marker::PhantomData;
use std::rc::Rc;
2019-03-03 00:24:14 +00:00
use actix_http::body::{Body, MessageBody};
use actix_http::{Extensions, Request};
2019-11-26 05:25:50 +00:00
use actix_service::boxed::{self, BoxServiceFactory};
2019-03-02 06:51:32 +00:00
use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, ServiceFactoryExt,
Transform,
2019-03-02 06:51:32 +00:00
};
2020-05-18 02:47:20 +00:00
use futures_util::future::FutureExt;
2019-03-02 06:51:32 +00:00
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
use crate::config::ServiceConfig;
use crate::data::{Data, DataFactory, FnDataFactory};
use crate::dev::ResourceDef;
use crate::error::Error;
2019-03-02 06:51:32 +00:00
use crate::resource::Resource;
use crate::route::Route;
use crate::service::{
2019-11-20 17:33:22 +00:00
AppServiceFactory, HttpServiceFactory, ServiceFactoryWrapper, ServiceRequest,
ServiceResponse,
};
2019-03-02 06:51:32 +00:00
2019-11-26 05:25:50 +00:00
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
2019-03-02 06:51:32 +00:00
2019-03-03 06:03:45 +00:00
/// Application builder - structure that follows the builder pattern
/// for building application instances.
pub struct App<T, B> {
endpoint: T,
2019-11-20 17:33:22 +00:00
services: Vec<Box<dyn AppServiceFactory>>,
default: Option<Rc<HttpNewService>>,
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
data_factories: Vec<FnDataFactory>,
external: Vec<ResourceDef>,
extensions: Extensions,
2021-01-04 00:49:02 +00:00
_phantom: PhantomData<B>,
2019-03-02 06:51:32 +00:00
}
impl App<AppEntry, Body> {
2019-03-17 03:17:27 +00:00
/// Create application builder. Application can be configured with a builder-like pattern.
#[allow(clippy::new_without_default)]
2019-03-02 06:51:32 +00:00
pub fn new() -> Self {
let fref = Rc::new(RefCell::new(None));
2019-03-02 19:53:05 +00:00
App {
endpoint: AppEntry::new(fref.clone()),
data_factories: Vec::new(),
services: Vec::new(),
default: None,
factory_ref: fref,
external: Vec::new(),
extensions: Extensions::new(),
2021-01-04 00:49:02 +00:00
_phantom: PhantomData,
2019-03-02 19:53:05 +00:00
}
2019-03-02 06:51:32 +00:00
}
}
impl<T, B> App<T, B>
2019-03-02 19:53:05 +00:00
where
B: MessageBody,
2019-11-20 17:33:22 +00:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
Response = ServiceResponse<B>,
Error = Error,
2019-03-02 19:53:05 +00:00
InitError = (),
>,
{
/// Set application data. Application data could be accessed
2019-03-17 03:17:27 +00:00
/// by using `Data<T>` extractor where `T` is data 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
2019-03-17 03:17:27 +00:00
/// instance for each thread, thus application data must be constructed
/// multiple times. If you want to share data between different
2019-12-20 11:36:48 +00:00
/// threads, a shared object should be used, e.g. `Arc`. Internally `Data` type
/// uses `Arc` so data could be created outside of app factory and clones could
/// be stored via `App::app_data()` method.
2019-03-03 06:11:24 +00:00
///
/// ```rust
/// use std::cell::Cell;
/// use actix_web::{web, App, HttpResponse, Responder};
2019-03-03 06:11:24 +00:00
///
2019-03-17 03:17:27 +00:00
/// struct MyData {
2019-03-03 06:11:24 +00:00
/// counter: Cell<usize>,
/// }
///
/// async fn index(data: web::Data<MyData>) -> impl Responder {
2019-03-17 03:17:27 +00:00
/// data.counter.set(data.counter.get() + 1);
/// HttpResponse::Ok()
2019-03-03 06:11:24 +00:00
/// }
///
2019-12-08 06:31:16 +00:00
/// let app = App::new()
/// .data(MyData{ counter: Cell::new(0) })
/// .service(
/// web::resource("/index.html").route(
/// web::get().to(index)));
2019-03-03 06:11:24 +00:00
/// ```
pub fn data<U: 'static>(self, data: U) -> Self {
self.app_data(Data::new(data))
2019-03-02 06:51:32 +00:00
}
/// Set application data factory. This function is
/// similar to `.data()` but it accepts data factory. Data object get
/// constructed asynchronously during application initialization.
2019-11-20 17:33:22 +00:00
pub fn data_factory<F, Out, D, E>(mut self, data: F) -> Self
where
F: Fn() -> Out + 'static,
2019-11-20 17:33:22 +00:00
Out: Future<Output = Result<D, E>> + 'static,
D: 'static,
E: std::fmt::Debug,
{
self.data_factories.push(Box::new(move || {
2019-11-20 17:33:22 +00:00
{
let fut = data();
async move {
match fut.await {
Err(e) => {
log::error!("Can not construct data instance: {:?}", e);
Err(())
}
Ok(data) => {
let data: Box<dyn DataFactory> = Box::new(Data::new(data));
Ok(data)
}
}
}
}
.boxed_local()
}));
self
}
/// Set application level arbitrary data item.
///
/// Application data stored with `App::app_data()` method is available
/// via `HttpRequest::app_data()` method at runtime.
///
/// This method could be used for storing `Data<T>` as well, in that case
/// data could be accessed by using `Data<T>` extractor.
pub fn app_data<U: 'static>(mut self, ext: U) -> Self {
self.extensions.insert(ext);
2019-06-05 02:43:39 +00:00
self
}
/// Run external configuration as part of the application building
/// process
///
/// This function is useful for moving parts of configuration to a
/// different module or even library. For example,
/// some of the resource's configuration could be moved to different module.
///
/// ```rust
/// use actix_web::{web, App, HttpResponse};
///
/// // this function could be located in different module
2019-04-15 14:32:49 +00:00
/// fn config(cfg: &mut web::ServiceConfig) {
/// cfg.service(web::resource("/test")
/// .route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// );
/// }
///
/// App::new()
/// .configure(config) // <- register resources
/// .route("/index.html", web::get().to(|| HttpResponse::Ok()));
/// ```
pub fn configure<F>(mut self, f: F) -> Self
where
F: FnOnce(&mut ServiceConfig),
{
2019-04-15 14:32:49 +00:00
let mut cfg = ServiceConfig::new();
f(&mut cfg);
self.services.extend(cfg.services);
self.external.extend(cfg.external);
self.extensions.extend(cfg.app_data);
self
}
/// Configure route for a specific path.
///
/// This is a simplified version of the `App::service()` method.
2019-03-17 03:17:27 +00:00
/// This method can be used multiple times with same path, in that case
/// multiple resources with one route would be registered for same resource path.
///
/// ```rust
/// use actix_web::{web, App, HttpResponse};
///
2019-11-21 15:34:04 +00:00
/// async 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<F>(mut self, factory: F) -> Self
where
F: HttpServiceFactory + 'static,
{
self.services
.push(Box::new(ServiceFactoryWrapper::new(factory)));
self
}
/// Default service to be used if no matching resource could be found.
///
/// It is possible to use services like `Resource`, `Route`.
///
/// ```rust
/// use actix_web::{web, App, HttpResponse};
///
2019-11-21 15:34:04 +00:00
/// async fn index() -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new()
/// .service(
/// web::resource("/index.html").route(web::get().to(index)))
/// .default_service(
/// web::route().to(|| HttpResponse::NotFound()));
/// }
/// ```
///
/// It is also possible to use static files as default service.
///
/// ```rust
/// use actix_web::{web, App, HttpResponse};
///
/// fn main() {
/// let app = App::new()
/// .service(
/// web::resource("/index.html").to(|| HttpResponse::Ok()))
/// .default_service(
2019-06-15 15:47:06 +00:00
/// web::to(|| HttpResponse::NotFound())
/// );
/// }
/// ```
pub fn default_service<F, U>(mut self, f: F) -> Self
where
F: IntoServiceFactory<U, ServiceRequest>,
2019-11-20 17:33:22 +00:00
U: ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
Response = ServiceResponse,
Error = Error,
> + 'static,
U::InitError: fmt::Debug,
{
// create and configure default resource
2019-11-20 17:33:22 +00:00
self.default = Some(Rc::new(boxed::factory(f.into_factory().map_init_err(
|e| log::error!("Can not construct default service: {:?}", e),
))));
self
}
2019-03-02 19:53:05 +00:00
/// 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};
///
2019-11-21 15:34:04 +00:00
/// async fn index(req: HttpRequest) -> Result<HttpResponse> {
/// let url = req.url_for("youtube", &["asdlkjqme"])?;
/// assert_eq!(url.as_str(), "https://youtube.com/watch/asdlkjqme");
/// Ok(HttpResponse::Ok().into())
/// }
///
/// fn main() {
/// let app = App::new()
/// .service(web::resource("/index.html").route(
/// web::get().to(index)))
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}");
/// }
/// ```
pub fn external_resource<N, U>(mut self, name: N, url: U) -> Self
where
N: AsRef<str>,
U: AsRef<str>,
{
let mut rdef = ResourceDef::new(url.as_ref());
*rdef.name_mut() = name.as_ref().to_string();
self.external.push(rdef);
self
}
/// Registers middleware, in the form of a middleware component (type),
/// that runs during inbound and/or outbound processing in the request
2020-04-21 03:09:35 +00:00
/// life-cycle (request -> response), modifying request/response as
/// necessary, across all requests managed by the *Application*.
2019-03-04 05:02:01 +00:00
///
/// Use middleware when you need to read or modify *every* request or
/// response in some way.
///
/// Notice that the keyword for registering middleware is `wrap`. As you
/// register middleware using `wrap` in the App builder, imagine wrapping
/// layers around an inner App. The first middleware layer exposed to a
/// Request is the outermost layer-- the *last* registered in
/// the builder chain. Consequently, the *first* middleware registered
/// in the builder chain is the *last* to execute during request processing.
2019-03-04 05:02:01 +00:00
///
/// ```rust
/// use actix_service::Service;
/// use actix_web::{middleware, web, App};
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};
2019-03-04 05:02:01 +00:00
///
2019-11-21 15:34:04 +00:00
/// async fn index() -> &'static str {
/// "Welcome!"
2019-03-04 05:02:01 +00:00
/// }
2019-03-02 06:51:32 +00:00
///
/// fn main() {
2019-03-03 06:03:45 +00:00
/// let app = App::new()
/// .wrap(middleware::Logger::default())
/// .route("/index.html", web::get().to(index));
2019-03-02 06:51:32 +00:00
/// }
/// ```
2019-11-20 17:33:22 +00:00
pub fn wrap<M, B1>(
2019-03-02 06:51:32 +00:00
self,
2019-11-20 17:33:22 +00:00
mw: M,
) -> App<
2019-11-20 17:33:22 +00:00
impl ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
2019-03-02 06:51:32 +00:00
Response = ServiceResponse<B1>,
Error = Error,
2019-03-02 06:51:32 +00:00
InitError = (),
>,
B1,
2019-03-02 06:51:32 +00:00
>
where
2019-03-05 05:37:57 +00:00
M: Transform<
2019-03-02 06:51:32 +00:00
T::Service,
ServiceRequest,
2019-03-02 06:51:32 +00:00
Response = ServiceResponse<B1>,
Error = Error,
2019-03-02 06:51:32 +00:00
InitError = (),
>,
B1: MessageBody,
{
App {
2019-11-20 17:33:22 +00:00
endpoint: apply(mw, self.endpoint),
data_factories: self.data_factories,
2019-03-02 06:51:32 +00:00
services: self.services,
default: self.default,
factory_ref: self.factory_ref,
external: self.external,
extensions: self.extensions,
2021-01-04 00:49:02 +00:00
_phantom: PhantomData,
2019-03-02 06:51:32 +00:00
}
}
/// Registers middleware, in the form of a closure, that runs during inbound
2020-04-21 03:09:35 +00:00
/// and/or outbound processing in the request life-cycle (request -> response),
/// modifying request/response as necessary, across all requests managed by
/// the *Application*.
///
/// Use middleware when you need to read or modify *every* request or response in some way.
///
/// ```rust
/// use actix_service::Service;
/// use actix_web::{web, App};
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};
///
2019-11-21 15:34:04 +00:00
/// async fn index() -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new()
2019-11-20 17:33:22 +00:00
/// .wrap_fn(|req, srv| {
/// let fut = srv.call(req);
/// async {
/// let mut res = fut.await?;
/// res.headers_mut().insert(
/// CONTENT_TYPE, HeaderValue::from_static("text/plain"),
/// );
2019-11-20 17:33:22 +00:00
/// Ok(res)
/// }
/// })
/// .route("/index.html", web::get().to(index));
/// }
/// ```
2019-03-25 20:43:02 +00:00
pub fn wrap_fn<B1, F, R>(
self,
mw: F,
) -> App<
2019-11-20 17:33:22 +00:00
impl ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
2019-03-25 20:43:02 +00:00
Response = ServiceResponse<B1>,
Error = Error,
InitError = (),
>,
B1,
2019-03-25 20:43:02 +00:00
>
where
B1: MessageBody,
F: Fn(ServiceRequest, &T::Service) -> R + Clone,
2019-11-20 17:33:22 +00:00
R: Future<Output = Result<ServiceResponse<B1>, Error>>,
2019-03-25 20:43:02 +00:00
{
2019-11-20 17:33:22 +00:00
App {
endpoint: apply_fn_factory(self.endpoint, mw),
data_factories: self.data_factories,
services: self.services,
default: self.default,
factory_ref: self.factory_ref,
external: self.external,
extensions: self.extensions,
2021-01-04 00:49:02 +00:00
_phantom: PhantomData,
2019-11-20 17:33:22 +00:00
}
2019-03-25 20:43:02 +00:00
}
2019-03-02 06:51:32 +00:00
}
impl<T, B> IntoServiceFactory<AppInit<T, B>, Request> for App<T, B>
2019-03-02 06:51:32 +00:00
where
B: MessageBody,
2019-11-20 17:33:22 +00:00
T: ServiceFactory<
ServiceRequest,
2019-05-12 15:34:51 +00:00
Config = (),
Response = ServiceResponse<B>,
Error = Error,
2019-03-02 19:53:05 +00:00
InitError = (),
>,
2021-01-06 11:35:30 +00:00
T::Future: 'static,
2019-03-02 06:51:32 +00:00
{
2019-11-20 17:33:22 +00:00
fn into_factory(self) -> AppInit<T, B> {
2019-03-02 19:53:05 +00:00
AppInit {
2021-01-06 11:35:30 +00:00
async_data_factories: self.data_factories.into_boxed_slice().into(),
endpoint: self.endpoint,
services: Rc::new(RefCell::new(self.services)),
external: RefCell::new(self.external),
default: self.default,
factory_ref: self.factory_ref,
extensions: RefCell::new(Some(self.extensions)),
2019-03-02 06:51:32 +00:00
}
2019-03-02 19:53:05 +00:00
}
}
#[cfg(test)]
mod tests {
use actix_service::Service;
2019-04-24 04:21:49 +00:00
use bytes::Bytes;
2020-05-21 08:56:53 +00:00
use futures_util::future::{err, ok};
use super::*;
2019-03-25 20:43:02 +00:00
use crate::http::{header, HeaderValue, Method, StatusCode};
2019-11-20 17:33:22 +00:00
use crate::middleware::DefaultHeaders;
2019-11-26 05:25:50 +00:00
use crate::service::ServiceRequest;
2020-05-21 08:56:53 +00:00
use crate::test::{
call_service, init_service, read_body, try_init_service, TestRequest,
};
2019-11-26 05:25:50 +00:00
use crate::{web, HttpRequest, HttpResponse};
#[actix_rt::test]
async fn test_default_resource() {
let srv = init_service(
App::new().service(web::resource("/test").to(HttpResponse::Ok)),
2019-11-26 05:25:50 +00:00
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/blah").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let srv = init_service(
2019-11-26 05:25:50 +00:00
App::new()
.service(web::resource("/test").to(HttpResponse::Ok))
2019-11-26 05:25:50 +00:00
.service(
web::resource("/test2")
.default_service(|r: ServiceRequest| {
ok(r.into_response(HttpResponse::Created()))
})
.route(web::get().to(HttpResponse::Ok)),
2019-11-26 05:25:50 +00:00
)
.default_service(|r: ServiceRequest| {
ok(r.into_response(HttpResponse::MethodNotAllowed()))
}),
)
.await;
2019-11-20 17:33:22 +00:00
2019-11-26 05:25:50 +00:00
let req = TestRequest::with_uri("/blah").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
2019-11-20 17:33:22 +00:00
2019-11-26 05:25:50 +00:00
let req = TestRequest::with_uri("/test2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
2019-11-20 17:33:22 +00:00
2019-11-26 05:25:50 +00:00
let req = TestRequest::with_uri("/test2")
.method(Method::POST)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_data_factory() {
let srv =
2019-11-26 05:25:50 +00:00
init_service(App::new().data_factory(|| ok::<_, ()>(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let srv =
2019-11-26 05:25:50 +00:00
init_service(App::new().data_factory(|| ok::<_, ()>(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
2019-03-25 20:43:02 +00:00
#[actix_rt::test]
async fn test_data_factory_errors() {
let srv =
try_init_service(App::new().data_factory(|| err::<u32, _>(())).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
2020-05-21 08:56:53 +00:00
assert!(srv.is_err());
}
#[actix_rt::test]
async fn test_extension() {
let srv = init_service(App::new().app_data(10usize).service(
web::resource("/").to(|req: HttpRequest| {
assert_eq!(*req.app_data::<usize>().unwrap(), 10);
HttpResponse::Ok()
}),
))
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_wrap() {
let srv = init_service(
2019-11-26 05:25:50 +00:00
App::new()
.wrap(
DefaultHeaders::new()
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
)
.route("/test", web::get().to(HttpResponse::Ok)),
2019-11-26 05:25:50 +00:00
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
2019-03-25 20:43:02 +00:00
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_router_wrap() {
let srv = init_service(
2019-11-26 05:25:50 +00:00
App::new()
.route("/test", web::get().to(HttpResponse::Ok))
2019-11-26 05:25:50 +00:00
.wrap(
DefaultHeaders::new()
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
2019-03-25 20:43:02 +00:00
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_wrap_fn() {
let srv = init_service(
2019-11-26 05:25:50 +00:00
App::new()
.wrap_fn(|req, srv| {
let fut = srv.call(req);
async move {
let mut res = fut.await?;
res.headers_mut().insert(
2019-11-20 17:33:22 +00:00
header::CONTENT_TYPE,
HeaderValue::from_static("0001"),
2019-11-26 05:25:50 +00:00
);
Ok(res)
}
})
.service(web::resource("/test").to(HttpResponse::Ok)),
2019-11-26 05:25:50 +00:00
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
2019-03-25 20:43:02 +00:00
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_router_wrap_fn() {
let srv = init_service(
2019-11-26 05:25:50 +00:00
App::new()
.route("/test", web::get().to(HttpResponse::Ok))
2019-11-26 05:25:50 +00:00
.wrap_fn(|req, srv| {
let fut = srv.call(req);
async {
let mut res = fut.await?;
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("0001"),
);
Ok(res)
}
}),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
2019-03-25 20:43:02 +00:00
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_external_resource() {
let srv = init_service(
2019-11-26 05:25:50 +00:00
App::new()
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
.route(
"/test",
web::get().to(|req: HttpRequest| {
HttpResponse::Ok().body(
req.url_for("youtube", &["12345"]).unwrap().to_string(),
)
2019-11-20 17:33:22 +00:00
}),
2019-11-26 05:25:50 +00:00
),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
2019-04-24 04:21:49 +00:00
}
}