mirror of
https://github.com/actix/actix-extras.git
synced 2024-11-28 01:32:57 +01:00
unify route and app data, it allows to provide global extractor config #775
This commit is contained in:
parent
01cfcf3b75
commit
fa78da8156
12
CHANGES.md
12
CHANGES.md
@ -1,11 +1,19 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.0-beta.3] - 2019-05-04
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
* Add helper function for executing futures `test::block_fn()`
|
* Add helper function for executing futures `test::block_fn()`
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
|
* Extractor configuration could be registered with `App::data()`
|
||||||
|
or with `Resource::data()` #775
|
||||||
|
|
||||||
|
* Route data is unified with app data, `Route::data()` moved to resource
|
||||||
|
level to `Resource::data()`
|
||||||
|
|
||||||
* CORS handling without headers #702
|
* CORS handling without headers #702
|
||||||
|
|
||||||
* Allow to construct `Data` instances to avoid double `Arc` for `Send + Sync` types.
|
* Allow to construct `Data` instances to avoid double `Arc` for `Send + Sync` types.
|
||||||
@ -14,6 +22,10 @@
|
|||||||
|
|
||||||
* Fix `NormalizePath` middleware impl #806
|
* Fix `NormalizePath` middleware impl #806
|
||||||
|
|
||||||
|
### Deleted
|
||||||
|
|
||||||
|
* `App::data_factory()` is deleted.
|
||||||
|
|
||||||
|
|
||||||
## [1.0.0-beta.2] - 2019-04-24
|
## [1.0.0-beta.2] - 2019-04-24
|
||||||
|
|
||||||
|
51
src/app.rs
51
src/app.rs
@ -100,19 +100,6 @@ where
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set application data factory. This function is
|
|
||||||
/// similar to `.data()` but it accepts data factory. Data object get
|
|
||||||
/// constructed asynchronously during application initialization.
|
|
||||||
pub fn data_factory<F, R>(mut self, data: F) -> Self
|
|
||||||
where
|
|
||||||
F: Fn() -> R + 'static,
|
|
||||||
R: IntoFuture + 'static,
|
|
||||||
R::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
self.data.push(Box::new(data));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run external configuration as part of the application building
|
/// Run external configuration as part of the application building
|
||||||
/// process
|
/// process
|
||||||
///
|
///
|
||||||
@ -425,9 +412,9 @@ where
|
|||||||
{
|
{
|
||||||
fn into_new_service(self) -> AppInit<T, B> {
|
fn into_new_service(self) -> AppInit<T, B> {
|
||||||
AppInit {
|
AppInit {
|
||||||
data: self.data,
|
data: Rc::new(self.data),
|
||||||
endpoint: self.endpoint,
|
endpoint: self.endpoint,
|
||||||
services: RefCell::new(self.services),
|
services: Rc::new(RefCell::new(self.services)),
|
||||||
external: RefCell::new(self.external),
|
external: RefCell::new(self.external),
|
||||||
default: self.default,
|
default: self.default,
|
||||||
factory_ref: self.factory_ref,
|
factory_ref: self.factory_ref,
|
||||||
@ -493,24 +480,24 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
// #[test]
|
||||||
fn test_data_factory() {
|
// fn test_data_factory() {
|
||||||
let mut srv =
|
// let mut srv =
|
||||||
init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service(
|
// init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service(
|
||||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||||
));
|
// ));
|
||||||
let req = TestRequest::default().to_request();
|
// let req = TestRequest::default().to_request();
|
||||||
let resp = block_on(srv.call(req)).unwrap();
|
// let resp = block_on(srv.call(req)).unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
// assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let mut srv =
|
// let mut srv =
|
||||||
init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service(
|
// init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service(
|
||||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||||
));
|
// ));
|
||||||
let req = TestRequest::default().to_request();
|
// let req = TestRequest::default().to_request();
|
||||||
let resp = block_on(srv.call(req)).unwrap();
|
// let resp = block_on(srv.call(req)).unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
}
|
// }
|
||||||
|
|
||||||
fn md<S, B>(
|
fn md<S, B>(
|
||||||
req: ServiceRequest,
|
req: ServiceRequest,
|
||||||
|
@ -2,7 +2,7 @@ use std::cell::RefCell;
|
|||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::{Request, Response};
|
use actix_http::{Extensions, Request, Response};
|
||||||
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
|
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
|
||||||
use actix_server_config::ServerConfig;
|
use actix_server_config::ServerConfig;
|
||||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||||
@ -11,7 +11,7 @@ use futures::future::{ok, Either, FutureResult};
|
|||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
|
|
||||||
use crate::config::{AppConfig, AppService};
|
use crate::config::{AppConfig, AppService};
|
||||||
use crate::data::{DataFactory, DataFactoryResult};
|
use crate::data::DataFactory;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::guard::Guard;
|
use crate::guard::Guard;
|
||||||
use crate::request::{HttpRequest, HttpRequestPool};
|
use crate::request::{HttpRequest, HttpRequestPool};
|
||||||
@ -38,9 +38,9 @@ where
|
|||||||
>,
|
>,
|
||||||
{
|
{
|
||||||
pub(crate) endpoint: T,
|
pub(crate) endpoint: T,
|
||||||
pub(crate) data: Vec<Box<DataFactory>>,
|
pub(crate) data: Rc<Vec<Box<DataFactory>>>,
|
||||||
pub(crate) config: RefCell<AppConfig>,
|
pub(crate) config: RefCell<AppConfig>,
|
||||||
pub(crate) services: RefCell<Vec<Box<ServiceFactory>>>,
|
pub(crate) services: Rc<RefCell<Vec<Box<ServiceFactory>>>>,
|
||||||
pub(crate) default: Option<Rc<HttpNewService>>,
|
pub(crate) default: Option<Rc<HttpNewService>>,
|
||||||
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
|
||||||
pub(crate) external: RefCell<Vec<ResourceDef>>,
|
pub(crate) external: RefCell<Vec<ResourceDef>>,
|
||||||
@ -70,6 +70,7 @@ where
|
|||||||
})))
|
})))
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// App config
|
||||||
{
|
{
|
||||||
let mut c = self.config.borrow_mut();
|
let mut c = self.config.borrow_mut();
|
||||||
let loc_cfg = Rc::get_mut(&mut c.0).unwrap();
|
let loc_cfg = Rc::get_mut(&mut c.0).unwrap();
|
||||||
@ -77,7 +78,11 @@ where
|
|||||||
loc_cfg.addr = cfg.local_addr();
|
loc_cfg.addr = cfg.local_addr();
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut config = AppService::new(self.config.borrow().clone(), default.clone());
|
let mut config = AppService::new(
|
||||||
|
self.config.borrow().clone(),
|
||||||
|
default.clone(),
|
||||||
|
self.data.clone(),
|
||||||
|
);
|
||||||
|
|
||||||
// register services
|
// register services
|
||||||
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
|
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
|
||||||
@ -86,12 +91,13 @@ where
|
|||||||
|
|
||||||
let mut rmap = ResourceMap::new(ResourceDef::new(""));
|
let mut rmap = ResourceMap::new(ResourceDef::new(""));
|
||||||
|
|
||||||
|
let (config, services) = config.into_services();
|
||||||
|
|
||||||
// complete pipeline creation
|
// complete pipeline creation
|
||||||
*self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
|
*self.factory_ref.borrow_mut() = Some(AppRoutingFactory {
|
||||||
default,
|
default,
|
||||||
services: Rc::new(
|
services: Rc::new(
|
||||||
config
|
services
|
||||||
.into_services()
|
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(mut rdef, srv, guards, nested)| {
|
.map(|(mut rdef, srv, guards, nested)| {
|
||||||
rmap.add(&mut rdef, nested);
|
rmap.add(&mut rdef, nested);
|
||||||
@ -110,11 +116,17 @@ where
|
|||||||
let rmap = Rc::new(rmap);
|
let rmap = Rc::new(rmap);
|
||||||
rmap.finish(rmap.clone());
|
rmap.finish(rmap.clone());
|
||||||
|
|
||||||
|
// create app data container
|
||||||
|
let mut data = Extensions::new();
|
||||||
|
for f in self.data.iter() {
|
||||||
|
f.create(&mut data);
|
||||||
|
}
|
||||||
|
|
||||||
AppInitResult {
|
AppInitResult {
|
||||||
endpoint: None,
|
endpoint: None,
|
||||||
endpoint_fut: self.endpoint.new_service(&()),
|
endpoint_fut: self.endpoint.new_service(&()),
|
||||||
data: self.data.iter().map(|s| s.construct()).collect(),
|
data: Rc::new(data),
|
||||||
config: self.config.borrow().clone(),
|
config,
|
||||||
rmap,
|
rmap,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -128,8 +140,8 @@ where
|
|||||||
endpoint: Option<T::Service>,
|
endpoint: Option<T::Service>,
|
||||||
endpoint_fut: T::Future,
|
endpoint_fut: T::Future,
|
||||||
rmap: Rc<ResourceMap>,
|
rmap: Rc<ResourceMap>,
|
||||||
data: Vec<Box<DataFactoryResult>>,
|
|
||||||
config: AppConfig,
|
config: AppConfig,
|
||||||
|
data: Rc<Extensions>,
|
||||||
_t: PhantomData<B>,
|
_t: PhantomData<B>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,27 +158,18 @@ where
|
|||||||
type Error = T::InitError;
|
type Error = T::InitError;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
let mut idx = 0;
|
|
||||||
let mut extensions = self.config.0.extensions.borrow_mut();
|
|
||||||
while idx < self.data.len() {
|
|
||||||
if let Async::Ready(_) = self.data[idx].poll_result(&mut extensions)? {
|
|
||||||
self.data.remove(idx);
|
|
||||||
} else {
|
|
||||||
idx += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.endpoint.is_none() {
|
if self.endpoint.is_none() {
|
||||||
if let Async::Ready(srv) = self.endpoint_fut.poll()? {
|
if let Async::Ready(srv) = self.endpoint_fut.poll()? {
|
||||||
self.endpoint = Some(srv);
|
self.endpoint = Some(srv);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.endpoint.is_some() && self.data.is_empty() {
|
if self.endpoint.is_some() {
|
||||||
Ok(Async::Ready(AppInitService {
|
Ok(Async::Ready(AppInitService {
|
||||||
service: self.endpoint.take().unwrap(),
|
service: self.endpoint.take().unwrap(),
|
||||||
rmap: self.rmap.clone(),
|
rmap: self.rmap.clone(),
|
||||||
config: self.config.clone(),
|
config: self.config.clone(),
|
||||||
|
data: self.data.clone(),
|
||||||
pool: HttpRequestPool::create(),
|
pool: HttpRequestPool::create(),
|
||||||
}))
|
}))
|
||||||
} else {
|
} else {
|
||||||
@ -183,6 +186,7 @@ where
|
|||||||
service: T,
|
service: T,
|
||||||
rmap: Rc<ResourceMap>,
|
rmap: Rc<ResourceMap>,
|
||||||
config: AppConfig,
|
config: AppConfig,
|
||||||
|
data: Rc<Extensions>,
|
||||||
pool: &'static HttpRequestPool,
|
pool: &'static HttpRequestPool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -207,6 +211,7 @@ where
|
|||||||
inner.path.get_mut().update(&head.uri);
|
inner.path.get_mut().update(&head.uri);
|
||||||
inner.path.reset();
|
inner.path.reset();
|
||||||
inner.head = head;
|
inner.head = head;
|
||||||
|
inner.app_data = self.data.clone();
|
||||||
req
|
req
|
||||||
} else {
|
} else {
|
||||||
HttpRequest::new(
|
HttpRequest::new(
|
||||||
@ -214,6 +219,7 @@ where
|
|||||||
head,
|
head,
|
||||||
self.rmap.clone(),
|
self.rmap.clone(),
|
||||||
self.config.clone(),
|
self.config.clone(),
|
||||||
|
self.data.clone(),
|
||||||
self.pool,
|
self.pool,
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
122
src/config.rs
122
src/config.rs
@ -1,11 +1,9 @@
|
|||||||
use std::cell::{Ref, RefCell};
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::Extensions;
|
use actix_http::Extensions;
|
||||||
use actix_router::ResourceDef;
|
use actix_router::ResourceDef;
|
||||||
use actix_service::{boxed, IntoNewService, NewService};
|
use actix_service::{boxed, IntoNewService, NewService};
|
||||||
use futures::IntoFuture;
|
|
||||||
|
|
||||||
use crate::data::{Data, DataFactory};
|
use crate::data::{Data, DataFactory};
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
@ -33,14 +31,20 @@ pub struct AppService {
|
|||||||
Option<Guards>,
|
Option<Guards>,
|
||||||
Option<Rc<ResourceMap>>,
|
Option<Rc<ResourceMap>>,
|
||||||
)>,
|
)>,
|
||||||
|
route_data: Rc<Vec<Box<DataFactory>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppService {
|
impl AppService {
|
||||||
/// Crate server settings instance
|
/// Crate server settings instance
|
||||||
pub(crate) fn new(config: AppConfig, default: Rc<HttpNewService>) -> Self {
|
pub(crate) fn new(
|
||||||
|
config: AppConfig,
|
||||||
|
default: Rc<HttpNewService>,
|
||||||
|
route_data: Rc<Vec<Box<DataFactory>>>,
|
||||||
|
) -> Self {
|
||||||
AppService {
|
AppService {
|
||||||
config,
|
config,
|
||||||
default,
|
default,
|
||||||
|
route_data,
|
||||||
root: true,
|
root: true,
|
||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
}
|
}
|
||||||
@ -53,13 +57,16 @@ impl AppService {
|
|||||||
|
|
||||||
pub(crate) fn into_services(
|
pub(crate) fn into_services(
|
||||||
self,
|
self,
|
||||||
) -> Vec<(
|
) -> (
|
||||||
|
AppConfig,
|
||||||
|
Vec<(
|
||||||
ResourceDef,
|
ResourceDef,
|
||||||
HttpNewService,
|
HttpNewService,
|
||||||
Option<Guards>,
|
Option<Guards>,
|
||||||
Option<Rc<ResourceMap>>,
|
Option<Rc<ResourceMap>>,
|
||||||
)> {
|
)>,
|
||||||
self.services
|
) {
|
||||||
|
(self.config, self.services)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn clone_config(&self) -> Self {
|
pub(crate) fn clone_config(&self) -> Self {
|
||||||
@ -68,6 +75,7 @@ impl AppService {
|
|||||||
default: self.default.clone(),
|
default: self.default.clone(),
|
||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
root: false,
|
root: false,
|
||||||
|
route_data: self.route_data.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,6 +89,15 @@ impl AppService {
|
|||||||
self.default.clone()
|
self.default.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set global route data
|
||||||
|
pub fn set_route_data(&self, extensions: &mut Extensions) -> bool {
|
||||||
|
for f in self.route_data.iter() {
|
||||||
|
f.create(extensions);
|
||||||
|
}
|
||||||
|
!self.route_data.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Register http service
|
||||||
pub fn register_service<F, S>(
|
pub fn register_service<F, S>(
|
||||||
&mut self,
|
&mut self,
|
||||||
rdef: ResourceDef,
|
rdef: ResourceDef,
|
||||||
@ -133,24 +150,12 @@ impl AppConfig {
|
|||||||
pub fn local_addr(&self) -> SocketAddr {
|
pub fn local_addr(&self) -> SocketAddr {
|
||||||
self.0.addr
|
self.0.addr
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resource map
|
|
||||||
pub fn rmap(&self) -> &ResourceMap {
|
|
||||||
&self.0.rmap
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Application extensions
|
|
||||||
pub fn extensions(&self) -> Ref<Extensions> {
|
|
||||||
self.0.extensions.borrow()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct AppConfigInner {
|
pub(crate) struct AppConfigInner {
|
||||||
pub(crate) secure: bool,
|
pub(crate) secure: bool,
|
||||||
pub(crate) host: String,
|
pub(crate) host: String,
|
||||||
pub(crate) addr: SocketAddr,
|
pub(crate) addr: SocketAddr,
|
||||||
pub(crate) rmap: ResourceMap,
|
|
||||||
pub(crate) extensions: RefCell<Extensions>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for AppConfigInner {
|
impl Default for AppConfigInner {
|
||||||
@ -159,8 +164,6 @@ impl Default for AppConfigInner {
|
|||||||
secure: false,
|
secure: false,
|
||||||
addr: "127.0.0.1:8080".parse().unwrap(),
|
addr: "127.0.0.1:8080".parse().unwrap(),
|
||||||
host: "localhost:8080".to_owned(),
|
host: "localhost:8080".to_owned(),
|
||||||
rmap: ResourceMap::new(ResourceDef::new("")),
|
|
||||||
extensions: RefCell::new(Extensions::new()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -188,23 +191,8 @@ impl ServiceConfig {
|
|||||||
/// by using `Data<T>` extractor where `T` is data type.
|
/// by using `Data<T>` extractor where `T` is data type.
|
||||||
///
|
///
|
||||||
/// This is same as `App::data()` method.
|
/// This is same as `App::data()` method.
|
||||||
pub fn data<S: 'static>(&mut self, data: S) -> &mut Self {
|
pub fn data<S: Into<Data<S>> + 'static>(&mut self, data: S) -> &mut Self {
|
||||||
self.data.push(Box::new(Data::new(data)));
|
self.data.push(Box::new(data.into()));
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set application data factory. This function is
|
|
||||||
/// similar to `.data()` but it accepts data factory. Data object get
|
|
||||||
/// constructed asynchronously during application initialization.
|
|
||||||
///
|
|
||||||
/// This is same as `App::data_dactory()` method.
|
|
||||||
pub fn data_factory<F, R>(&mut self, data: F) -> &mut Self
|
|
||||||
where
|
|
||||||
F: Fn() -> R + 'static,
|
|
||||||
R: IntoFuture + 'static,
|
|
||||||
R::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
self.data.push(Box::new(data));
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -254,8 +242,6 @@ impl ServiceConfig {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use actix_service::Service;
|
use actix_service::Service;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::Future;
|
|
||||||
use tokio_timer::sleep;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::http::{Method, StatusCode};
|
use crate::http::{Method, StatusCode};
|
||||||
@ -277,37 +263,37 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
// #[test]
|
||||||
fn test_data_factory() {
|
// fn test_data_factory() {
|
||||||
let cfg = |cfg: &mut ServiceConfig| {
|
// let cfg = |cfg: &mut ServiceConfig| {
|
||||||
cfg.data_factory(|| {
|
// cfg.data_factory(|| {
|
||||||
sleep(std::time::Duration::from_millis(50)).then(|_| {
|
// sleep(std::time::Duration::from_millis(50)).then(|_| {
|
||||||
println!("READY");
|
// println!("READY");
|
||||||
Ok::<_, ()>(10usize)
|
// Ok::<_, ()>(10usize)
|
||||||
})
|
// })
|
||||||
});
|
// });
|
||||||
};
|
// };
|
||||||
|
|
||||||
let mut srv =
|
// let mut srv =
|
||||||
init_service(App::new().configure(cfg).service(
|
// init_service(App::new().configure(cfg).service(
|
||||||
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
|
||||||
));
|
// ));
|
||||||
let req = TestRequest::default().to_request();
|
// let req = TestRequest::default().to_request();
|
||||||
let resp = block_on(srv.call(req)).unwrap();
|
// let resp = block_on(srv.call(req)).unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
// assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
let cfg2 = |cfg: &mut ServiceConfig| {
|
// let cfg2 = |cfg: &mut ServiceConfig| {
|
||||||
cfg.data_factory(|| Ok::<_, ()>(10u32));
|
// cfg.data_factory(|| Ok::<_, ()>(10u32));
|
||||||
};
|
// };
|
||||||
let mut srv = init_service(
|
// let mut srv = init_service(
|
||||||
App::new()
|
// App::new()
|
||||||
.service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()))
|
// .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()))
|
||||||
.configure(cfg2),
|
// .configure(cfg2),
|
||||||
);
|
// );
|
||||||
let req = TestRequest::default().to_request();
|
// let req = TestRequest::default().to_request();
|
||||||
let resp = block_on(srv.call(req)).unwrap();
|
// let resp = block_on(srv.call(req)).unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
}
|
// }
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_external_resource() {
|
fn test_external_resource() {
|
||||||
|
179
src/data.rs
179
src/data.rs
@ -3,7 +3,6 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use actix_http::error::{Error, ErrorInternalServerError};
|
use actix_http::error::{Error, ErrorInternalServerError};
|
||||||
use actix_http::Extensions;
|
use actix_http::Extensions;
|
||||||
use futures::{Async, Future, IntoFuture, Poll};
|
|
||||||
|
|
||||||
use crate::dev::Payload;
|
use crate::dev::Payload;
|
||||||
use crate::extract::FromRequest;
|
use crate::extract::FromRequest;
|
||||||
@ -11,11 +10,7 @@ use crate::request::HttpRequest;
|
|||||||
|
|
||||||
/// Application data factory
|
/// Application data factory
|
||||||
pub(crate) trait DataFactory {
|
pub(crate) trait DataFactory {
|
||||||
fn construct(&self) -> Box<DataFactoryResult>;
|
fn create(&self, extensions: &mut Extensions) -> bool;
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) trait DataFactoryResult {
|
|
||||||
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Application data.
|
/// Application data.
|
||||||
@ -111,8 +106,8 @@ impl<T: 'static> FromRequest for Data<T> {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||||
if let Some(st) = req.app_config().extensions().get::<Data<T>>() {
|
if let Some(st) = req.get_app_data::<T>() {
|
||||||
Ok(st.clone())
|
Ok(st)
|
||||||
} else {
|
} else {
|
||||||
log::debug!(
|
log::debug!(
|
||||||
"Failed to construct App-level Data extractor. \
|
"Failed to construct App-level Data extractor. \
|
||||||
@ -127,142 +122,12 @@ impl<T: 'static> FromRequest for Data<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: 'static> DataFactory for Data<T> {
|
impl<T: 'static> DataFactory for Data<T> {
|
||||||
fn construct(&self) -> Box<DataFactoryResult> {
|
fn create(&self, extensions: &mut Extensions) -> bool {
|
||||||
Box::new(DataFut { st: self.clone() })
|
if !extensions.contains::<Data<T>>() {
|
||||||
}
|
let _ = extensions.insert(Data(self.0.clone()));
|
||||||
}
|
true
|
||||||
|
|
||||||
struct DataFut<T> {
|
|
||||||
st: Data<T>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: 'static> DataFactoryResult for DataFut<T> {
|
|
||||||
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
|
|
||||||
extensions.insert(self.st.clone());
|
|
||||||
Ok(Async::Ready(()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F, Out> DataFactory for F
|
|
||||||
where
|
|
||||||
F: Fn() -> Out + 'static,
|
|
||||||
Out: IntoFuture + 'static,
|
|
||||||
Out::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
fn construct(&self) -> Box<DataFactoryResult> {
|
|
||||||
Box::new(DataFactoryFut {
|
|
||||||
fut: (*self)().into_future(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct DataFactoryFut<T, F>
|
|
||||||
where
|
|
||||||
F: Future<Item = T>,
|
|
||||||
F::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
fut: F,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: 'static, F> DataFactoryResult for DataFactoryFut<T, F>
|
|
||||||
where
|
|
||||||
F: Future<Item = T>,
|
|
||||||
F::Error: std::fmt::Debug,
|
|
||||||
{
|
|
||||||
fn poll_result(&mut self, extensions: &mut Extensions) -> Poll<(), ()> {
|
|
||||||
match self.fut.poll() {
|
|
||||||
Ok(Async::Ready(s)) => {
|
|
||||||
extensions.insert(Data::new(s));
|
|
||||||
Ok(Async::Ready(()))
|
|
||||||
}
|
|
||||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Can not construct application state: {:?}", e);
|
|
||||||
Err(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Route data.
|
|
||||||
///
|
|
||||||
/// Route data is an arbitrary data attached to specific route.
|
|
||||||
/// Route data could be added to route during route configuration process
|
|
||||||
/// with `Route::data()` method. Route data is also used as an extractor
|
|
||||||
/// configuration storage. Route data could be accessed in handler
|
|
||||||
/// via `RouteData<T>` extractor.
|
|
||||||
///
|
|
||||||
/// If route data is not set for a handler, using `RouteData` extractor
|
|
||||||
/// would cause *Internal Server Error* response.
|
|
||||||
///
|
|
||||||
/// ```rust
|
|
||||||
/// # use std::cell::Cell;
|
|
||||||
/// use actix_web::{web, App};
|
|
||||||
///
|
|
||||||
/// struct MyData {
|
|
||||||
/// counter: Cell<usize>,
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// /// Use `RouteData<T>` extractor to access data in handler.
|
|
||||||
/// fn index(data: web::RouteData<MyData>) {
|
|
||||||
/// data.counter.set(data.counter.get() + 1);
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// fn main() {
|
|
||||||
/// let app = App::new().service(
|
|
||||||
/// web::resource("/index.html").route(
|
|
||||||
/// web::get()
|
|
||||||
/// // Store `MyData` in route storage
|
|
||||||
/// .data(MyData{ counter: Cell::new(0) })
|
|
||||||
/// // Route data could be used as extractor configuration storage,
|
|
||||||
/// // limit size of the payload
|
|
||||||
/// .data(web::PayloadConfig::new(4096))
|
|
||||||
/// // register handler
|
|
||||||
/// .to(index)
|
|
||||||
/// ));
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub struct RouteData<T>(Arc<T>);
|
|
||||||
|
|
||||||
impl<T> RouteData<T> {
|
|
||||||
pub(crate) fn new(state: T) -> RouteData<T> {
|
|
||||||
RouteData(Arc::new(state))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get referecnce to inner data object.
|
|
||||||
pub fn get_ref(&self) -> &T {
|
|
||||||
self.0.as_ref()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Deref for RouteData<T> {
|
|
||||||
type Target = T;
|
|
||||||
|
|
||||||
fn deref(&self) -> &T {
|
|
||||||
self.0.as_ref()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Clone for RouteData<T> {
|
|
||||||
fn clone(&self) -> RouteData<T> {
|
|
||||||
RouteData(self.0.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: 'static> FromRequest for RouteData<T> {
|
|
||||||
type Config = ();
|
|
||||||
type Error = Error;
|
|
||||||
type Future = Result<Self, Error>;
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
|
||||||
if let Some(st) = req.route_data::<T>() {
|
|
||||||
Ok(st.clone())
|
|
||||||
} else {
|
} else {
|
||||||
log::debug!("Failed to construct Route-level Data extractor");
|
false
|
||||||
Err(ErrorInternalServerError(
|
|
||||||
"Route data is not configured, to configure use Route::data()",
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -297,8 +162,9 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_route_data_extractor() {
|
fn test_route_data_extractor() {
|
||||||
let mut srv = init_service(App::new().service(web::resource("/").route(
|
let mut srv =
|
||||||
web::get().data(10usize).to(|data: web::RouteData<usize>| {
|
init_service(App::new().service(web::resource("/").data(10usize).route(
|
||||||
|
web::get().to(|data: web::Data<usize>| {
|
||||||
let _ = data.clone();
|
let _ = data.clone();
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
}),
|
}),
|
||||||
@ -311,15 +177,30 @@ mod tests {
|
|||||||
// different type
|
// different type
|
||||||
let mut srv = init_service(
|
let mut srv = init_service(
|
||||||
App::new().service(
|
App::new().service(
|
||||||
web::resource("/").route(
|
web::resource("/")
|
||||||
web::get()
|
|
||||||
.data(10u32)
|
.data(10u32)
|
||||||
.to(|_: web::RouteData<usize>| HttpResponse::Ok()),
|
.route(web::get().to(|_: web::Data<usize>| HttpResponse::Ok())),
|
||||||
),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
let req = TestRequest::default().to_request();
|
let req = TestRequest::default().to_request();
|
||||||
let resp = block_on(srv.call(req)).unwrap();
|
let resp = block_on(srv.call(req)).unwrap();
|
||||||
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_override_data() {
|
||||||
|
let mut srv = init_service(App::new().data(1usize).service(
|
||||||
|
web::resource("/").data(10usize).route(web::get().to(
|
||||||
|
|data: web::Data<usize>| {
|
||||||
|
assert_eq!(*data, 10);
|
||||||
|
let _ = data.clone();
|
||||||
|
HttpResponse::Ok()
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
));
|
||||||
|
|
||||||
|
let req = TestRequest::default().to_request();
|
||||||
|
let resp = block_on(srv.call(req)).unwrap();
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -283,7 +283,7 @@ mod tests {
|
|||||||
header::CONTENT_TYPE,
|
header::CONTENT_TYPE,
|
||||||
"application/x-www-form-urlencoded",
|
"application/x-www-form-urlencoded",
|
||||||
)
|
)
|
||||||
.route_data(FormConfig::default().limit(4096))
|
.data(FormConfig::default().limit(4096))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap();
|
let r = block_on(Option::<Form<Info>>::from_request(&req, &mut pl)).unwrap();
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
use std::cell::RefCell;
|
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::rc::Rc;
|
|
||||||
|
|
||||||
use actix_http::{Error, Extensions, Payload, Response};
|
use actix_http::{Error, Payload, Response};
|
||||||
use actix_service::{NewService, Service, Void};
|
use actix_service::{NewService, Service, Void};
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||||
@ -267,15 +265,13 @@ where
|
|||||||
|
|
||||||
/// Extract arguments from request
|
/// Extract arguments from request
|
||||||
pub struct Extract<T: FromRequest, S> {
|
pub struct Extract<T: FromRequest, S> {
|
||||||
config: Rc<RefCell<Option<Rc<Extensions>>>>,
|
|
||||||
service: S,
|
service: S,
|
||||||
_t: PhantomData<T>,
|
_t: PhantomData<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: FromRequest, S> Extract<T, S> {
|
impl<T: FromRequest, S> Extract<T, S> {
|
||||||
pub fn new(config: Rc<RefCell<Option<Rc<Extensions>>>>, service: S) -> Self {
|
pub fn new(service: S) -> Self {
|
||||||
Extract {
|
Extract {
|
||||||
config,
|
|
||||||
service,
|
service,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
@ -297,14 +293,12 @@ where
|
|||||||
fn new_service(&self, _: &()) -> Self::Future {
|
fn new_service(&self, _: &()) -> Self::Future {
|
||||||
ok(ExtractService {
|
ok(ExtractService {
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
config: self.config.borrow().clone(),
|
|
||||||
service: self.service.clone(),
|
service: self.service.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ExtractService<T: FromRequest, S> {
|
pub struct ExtractService<T: FromRequest, S> {
|
||||||
config: Option<Rc<Extensions>>,
|
|
||||||
service: S,
|
service: S,
|
||||||
_t: PhantomData<T>,
|
_t: PhantomData<T>,
|
||||||
}
|
}
|
||||||
@ -324,8 +318,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||||
let (mut req, mut payload) = req.into_parts();
|
let (req, mut payload) = req.into_parts();
|
||||||
req.set_route_data(self.config.clone());
|
|
||||||
let fut = T::from_request(&req, &mut payload).into_future();
|
let fut = T::from_request(&req, &mut payload).into_future();
|
||||||
|
|
||||||
ExtractResponse {
|
ExtractResponse {
|
||||||
|
@ -870,10 +870,7 @@ mod tests {
|
|||||||
|
|
||||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||||
.method(Method::OPTIONS)
|
.method(Method::OPTIONS)
|
||||||
.header(
|
.header(header::ACCESS_CONTROL_REQUEST_HEADERS, "X-Not-Allowed")
|
||||||
header::ACCESS_CONTROL_REQUEST_HEADERS,
|
|
||||||
"X-Not-Allowed",
|
|
||||||
)
|
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
|
|
||||||
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
assert!(cors.inner.validate_allowed_method(req.head()).is_err());
|
||||||
|
@ -7,7 +7,7 @@ use actix_http::{Error, Extensions, HttpMessage, Message, Payload, RequestHead};
|
|||||||
use actix_router::{Path, Url};
|
use actix_router::{Path, Url};
|
||||||
|
|
||||||
use crate::config::AppConfig;
|
use crate::config::AppConfig;
|
||||||
use crate::data::{Data, RouteData};
|
use crate::data::Data;
|
||||||
use crate::error::UrlGenerationError;
|
use crate::error::UrlGenerationError;
|
||||||
use crate::extract::FromRequest;
|
use crate::extract::FromRequest;
|
||||||
use crate::info::ConnectionInfo;
|
use crate::info::ConnectionInfo;
|
||||||
@ -20,9 +20,9 @@ pub struct HttpRequest(pub(crate) Rc<HttpRequestInner>);
|
|||||||
pub(crate) struct HttpRequestInner {
|
pub(crate) struct HttpRequestInner {
|
||||||
pub(crate) head: Message<RequestHead>,
|
pub(crate) head: Message<RequestHead>,
|
||||||
pub(crate) path: Path<Url>,
|
pub(crate) path: Path<Url>,
|
||||||
|
pub(crate) app_data: Rc<Extensions>,
|
||||||
rmap: Rc<ResourceMap>,
|
rmap: Rc<ResourceMap>,
|
||||||
config: AppConfig,
|
config: AppConfig,
|
||||||
route_data: Option<Rc<Extensions>>,
|
|
||||||
pool: &'static HttpRequestPool,
|
pool: &'static HttpRequestPool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -33,6 +33,7 @@ impl HttpRequest {
|
|||||||
head: Message<RequestHead>,
|
head: Message<RequestHead>,
|
||||||
rmap: Rc<ResourceMap>,
|
rmap: Rc<ResourceMap>,
|
||||||
config: AppConfig,
|
config: AppConfig,
|
||||||
|
app_data: Rc<Extensions>,
|
||||||
pool: &'static HttpRequestPool,
|
pool: &'static HttpRequestPool,
|
||||||
) -> HttpRequest {
|
) -> HttpRequest {
|
||||||
HttpRequest(Rc::new(HttpRequestInner {
|
HttpRequest(Rc::new(HttpRequestInner {
|
||||||
@ -40,8 +41,8 @@ impl HttpRequest {
|
|||||||
path,
|
path,
|
||||||
rmap,
|
rmap,
|
||||||
config,
|
config,
|
||||||
|
app_data,
|
||||||
pool,
|
pool,
|
||||||
route_data: None,
|
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -195,27 +196,23 @@ impl HttpRequest {
|
|||||||
|
|
||||||
/// Get an application data stored with `App::data()` method during
|
/// Get an application data stored with `App::data()` method during
|
||||||
/// application configuration.
|
/// application configuration.
|
||||||
pub fn app_data<T: 'static>(&self) -> Option<Data<T>> {
|
pub fn app_data<T: 'static>(&self) -> Option<&T> {
|
||||||
if let Some(st) = self.0.config.extensions().get::<Data<T>>() {
|
if let Some(st) = self.0.app_data.get::<Data<T>>() {
|
||||||
|
Some(&st)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get an application data stored with `App::data()` method during
|
||||||
|
/// application configuration.
|
||||||
|
pub fn get_app_data<T: 'static>(&self) -> Option<Data<T>> {
|
||||||
|
if let Some(st) = self.0.app_data.get::<Data<T>>() {
|
||||||
Some(st.clone())
|
Some(st.clone())
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load route data. Route data could be set during
|
|
||||||
/// route configuration with `Route::data()` method.
|
|
||||||
pub fn route_data<T: 'static>(&self) -> Option<&RouteData<T>> {
|
|
||||||
if let Some(ref ext) = self.0.route_data {
|
|
||||||
ext.get::<RouteData<T>>()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn set_route_data(&mut self, data: Option<Rc<Extensions>>) {
|
|
||||||
Rc::get_mut(&mut self.0).unwrap().route_data = data;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpMessage for HttpRequest {
|
impl HttpMessage for HttpRequest {
|
||||||
|
@ -2,7 +2,7 @@ use std::cell::RefCell;
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::{Error, Response};
|
use actix_http::{Error, Extensions, Response};
|
||||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||||
use actix_service::{
|
use actix_service::{
|
||||||
apply_transform, IntoNewService, IntoTransform, NewService, Service, Transform,
|
apply_transform, IntoNewService, IntoTransform, NewService, Service, Transform,
|
||||||
@ -10,6 +10,7 @@ use actix_service::{
|
|||||||
use futures::future::{ok, Either, FutureResult};
|
use futures::future::{ok, Either, FutureResult};
|
||||||
use futures::{Async, Future, IntoFuture, Poll};
|
use futures::{Async, Future, IntoFuture, Poll};
|
||||||
|
|
||||||
|
use crate::data::Data;
|
||||||
use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef};
|
use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef};
|
||||||
use crate::extract::FromRequest;
|
use crate::extract::FromRequest;
|
||||||
use crate::guard::Guard;
|
use crate::guard::Guard;
|
||||||
@ -48,6 +49,7 @@ pub struct Resource<T = ResourceEndpoint> {
|
|||||||
rdef: String,
|
rdef: String,
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
routes: Vec<Route>,
|
routes: Vec<Route>,
|
||||||
|
data: Option<Extensions>,
|
||||||
guards: Vec<Box<Guard>>,
|
guards: Vec<Box<Guard>>,
|
||||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||||
factory_ref: Rc<RefCell<Option<ResourceFactory>>>,
|
factory_ref: Rc<RefCell<Option<ResourceFactory>>>,
|
||||||
@ -64,6 +66,7 @@ impl Resource {
|
|||||||
endpoint: ResourceEndpoint::new(fref.clone()),
|
endpoint: ResourceEndpoint::new(fref.clone()),
|
||||||
factory_ref: fref,
|
factory_ref: fref,
|
||||||
guards: Vec::new(),
|
guards: Vec::new(),
|
||||||
|
data: None,
|
||||||
default: Rc::new(RefCell::new(None)),
|
default: Rc::new(RefCell::new(None)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -154,7 +157,42 @@ where
|
|||||||
/// # fn delete_handler() {}
|
/// # fn delete_handler() {}
|
||||||
/// ```
|
/// ```
|
||||||
pub fn route(mut self, route: Route) -> Self {
|
pub fn route(mut self, route: Route) -> Self {
|
||||||
self.routes.push(route.finish());
|
self.routes.push(route);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Provide resource specific data. This method allows to add extractor
|
||||||
|
/// configuration or specific state available via `Data<T>` extractor.
|
||||||
|
/// Provided data is available for all routes registered for the current resource.
|
||||||
|
/// Resource data overrides data registered by `App::data()` method.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// use actix_web::{web, App, FromRequest};
|
||||||
|
///
|
||||||
|
/// /// extract text data from request
|
||||||
|
/// fn index(body: String) -> String {
|
||||||
|
/// format!("Body {}!", body)
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn main() {
|
||||||
|
/// let app = App::new().service(
|
||||||
|
/// web::resource("/index.html")
|
||||||
|
/// // limit size of the payload
|
||||||
|
/// .data(String::configure(|cfg| {
|
||||||
|
/// cfg.limit(4096)
|
||||||
|
/// }))
|
||||||
|
/// .route(
|
||||||
|
/// web::get()
|
||||||
|
/// // register handler
|
||||||
|
/// .to(index)
|
||||||
|
/// ));
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||||
|
if self.data.is_none() {
|
||||||
|
self.data = Some(Extensions::new());
|
||||||
|
}
|
||||||
|
self.data.as_mut().unwrap().insert(Data::new(data));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -260,6 +298,7 @@ where
|
|||||||
guards: self.guards,
|
guards: self.guards,
|
||||||
routes: self.routes,
|
routes: self.routes,
|
||||||
default: self.default,
|
default: self.default,
|
||||||
|
data: self.data,
|
||||||
factory_ref: self.factory_ref,
|
factory_ref: self.factory_ref,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -361,6 +400,10 @@ where
|
|||||||
if let Some(ref name) = self.name {
|
if let Some(ref name) = self.name {
|
||||||
*rdef.name_mut() = name.clone();
|
*rdef.name_mut() = name.clone();
|
||||||
}
|
}
|
||||||
|
// custom app data storage
|
||||||
|
if let Some(ref mut ext) = self.data {
|
||||||
|
config.set_route_data(ext);
|
||||||
|
}
|
||||||
config.register_service(rdef, guards, self, None)
|
config.register_service(rdef, guards, self, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -377,6 +420,7 @@ where
|
|||||||
fn into_new_service(self) -> T {
|
fn into_new_service(self) -> T {
|
||||||
*self.factory_ref.borrow_mut() = Some(ResourceFactory {
|
*self.factory_ref.borrow_mut() = Some(ResourceFactory {
|
||||||
routes: self.routes,
|
routes: self.routes,
|
||||||
|
data: self.data.map(|data| Rc::new(data)),
|
||||||
default: self.default,
|
default: self.default,
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -386,6 +430,7 @@ where
|
|||||||
|
|
||||||
pub struct ResourceFactory {
|
pub struct ResourceFactory {
|
||||||
routes: Vec<Route>,
|
routes: Vec<Route>,
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -410,6 +455,7 @@ impl NewService for ResourceFactory {
|
|||||||
.iter()
|
.iter()
|
||||||
.map(|route| CreateRouteServiceItem::Future(route.new_service(&())))
|
.map(|route| CreateRouteServiceItem::Future(route.new_service(&())))
|
||||||
.collect(),
|
.collect(),
|
||||||
|
data: self.data.clone(),
|
||||||
default: None,
|
default: None,
|
||||||
default_fut,
|
default_fut,
|
||||||
}
|
}
|
||||||
@ -423,6 +469,7 @@ enum CreateRouteServiceItem {
|
|||||||
|
|
||||||
pub struct CreateResourceService {
|
pub struct CreateResourceService {
|
||||||
fut: Vec<CreateRouteServiceItem>,
|
fut: Vec<CreateRouteServiceItem>,
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
default: Option<HttpService>,
|
default: Option<HttpService>,
|
||||||
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
|
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
|
||||||
}
|
}
|
||||||
@ -467,6 +514,7 @@ impl Future for CreateResourceService {
|
|||||||
.collect();
|
.collect();
|
||||||
Ok(Async::Ready(ResourceService {
|
Ok(Async::Ready(ResourceService {
|
||||||
routes,
|
routes,
|
||||||
|
data: self.data.clone(),
|
||||||
default: self.default.take(),
|
default: self.default.take(),
|
||||||
}))
|
}))
|
||||||
} else {
|
} else {
|
||||||
@ -477,6 +525,7 @@ impl Future for CreateResourceService {
|
|||||||
|
|
||||||
pub struct ResourceService {
|
pub struct ResourceService {
|
||||||
routes: Vec<RouteService>,
|
routes: Vec<RouteService>,
|
||||||
|
data: Option<Rc<Extensions>>,
|
||||||
default: Option<HttpService>,
|
default: Option<HttpService>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -496,6 +545,9 @@ impl Service for ResourceService {
|
|||||||
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
||||||
for route in self.routes.iter_mut() {
|
for route in self.routes.iter_mut() {
|
||||||
if route.check(&mut req) {
|
if route.check(&mut req) {
|
||||||
|
if let Some(ref data) = self.data {
|
||||||
|
req.set_data_container(data.clone());
|
||||||
|
}
|
||||||
return route.call(req);
|
return route.call(req);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
66
src/route.rs
66
src/route.rs
@ -1,12 +1,10 @@
|
|||||||
use std::cell::RefCell;
|
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::{http::Method, Error, Extensions};
|
use actix_http::{http::Method, Error};
|
||||||
use actix_service::{NewService, Service};
|
use actix_service::{NewService, Service};
|
||||||
use futures::future::{ok, Either, FutureResult};
|
use futures::future::{ok, Either, FutureResult};
|
||||||
use futures::{Async, Future, IntoFuture, Poll};
|
use futures::{Async, Future, IntoFuture, Poll};
|
||||||
|
|
||||||
use crate::data::RouteData;
|
|
||||||
use crate::extract::FromRequest;
|
use crate::extract::FromRequest;
|
||||||
use crate::guard::{self, Guard};
|
use crate::guard::{self, Guard};
|
||||||
use crate::handler::{AsyncFactory, AsyncHandler, Extract, Factory, Handler};
|
use crate::handler::{AsyncFactory, AsyncHandler, Extract, Factory, Handler};
|
||||||
@ -44,30 +42,19 @@ type BoxedRouteNewService<Req, Res> = Box<
|
|||||||
pub struct Route {
|
pub struct Route {
|
||||||
service: BoxedRouteNewService<ServiceRequest, ServiceResponse>,
|
service: BoxedRouteNewService<ServiceRequest, ServiceResponse>,
|
||||||
guards: Rc<Vec<Box<Guard>>>,
|
guards: Rc<Vec<Box<Guard>>>,
|
||||||
data: Option<Extensions>,
|
|
||||||
data_ref: Rc<RefCell<Option<Rc<Extensions>>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Route {
|
impl Route {
|
||||||
/// Create new route which matches any request.
|
/// Create new route which matches any request.
|
||||||
pub fn new() -> Route {
|
pub fn new() -> Route {
|
||||||
let data_ref = Rc::new(RefCell::new(None));
|
|
||||||
Route {
|
Route {
|
||||||
service: Box::new(RouteNewService::new(Extract::new(
|
service: Box::new(RouteNewService::new(Extract::new(Handler::new(|| {
|
||||||
data_ref.clone(),
|
HttpResponse::NotFound()
|
||||||
Handler::new(|| HttpResponse::NotFound()),
|
})))),
|
||||||
))),
|
|
||||||
guards: Rc::new(Vec::new()),
|
guards: Rc::new(Vec::new()),
|
||||||
data: None,
|
|
||||||
data_ref,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn finish(mut self) -> Self {
|
|
||||||
*self.data_ref.borrow_mut() = self.data.take().map(Rc::new);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn take_guards(&mut self) -> Vec<Box<Guard>> {
|
pub(crate) fn take_guards(&mut self) -> Vec<Box<Guard>> {
|
||||||
std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new())
|
std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new())
|
||||||
}
|
}
|
||||||
@ -239,10 +226,8 @@ impl Route {
|
|||||||
T: FromRequest + 'static,
|
T: FromRequest + 'static,
|
||||||
R: Responder + 'static,
|
R: Responder + 'static,
|
||||||
{
|
{
|
||||||
self.service = Box::new(RouteNewService::new(Extract::new(
|
self.service =
|
||||||
self.data_ref.clone(),
|
Box::new(RouteNewService::new(Extract::new(Handler::new(handler))));
|
||||||
Handler::new(handler),
|
|
||||||
)));
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -281,42 +266,9 @@ impl Route {
|
|||||||
R::Item: Responder,
|
R::Item: Responder,
|
||||||
R::Error: Into<Error>,
|
R::Error: Into<Error>,
|
||||||
{
|
{
|
||||||
self.service = Box::new(RouteNewService::new(Extract::new(
|
self.service = Box::new(RouteNewService::new(Extract::new(AsyncHandler::new(
|
||||||
self.data_ref.clone(),
|
handler,
|
||||||
AsyncHandler::new(handler),
|
))));
|
||||||
)));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Provide route specific data. This method allows to add extractor
|
|
||||||
/// configuration or specific state available via `RouteData<T>` extractor.
|
|
||||||
///
|
|
||||||
/// ```rust
|
|
||||||
/// use actix_web::{web, App, FromRequest};
|
|
||||||
///
|
|
||||||
/// /// extract text data from request
|
|
||||||
/// fn index(body: String) -> String {
|
|
||||||
/// format!("Body {}!", body)
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// fn main() {
|
|
||||||
/// let app = App::new().service(
|
|
||||||
/// web::resource("/index.html").route(
|
|
||||||
/// web::get()
|
|
||||||
/// // limit size of the payload
|
|
||||||
/// .data(String::configure(|cfg| {
|
|
||||||
/// cfg.limit(4096)
|
|
||||||
/// }))
|
|
||||||
/// // register handler
|
|
||||||
/// .to(index)
|
|
||||||
/// ));
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
pub fn data<T: 'static>(mut self, data: T) -> Self {
|
|
||||||
if self.data.is_none() {
|
|
||||||
self.data = Some(Extensions::new());
|
|
||||||
}
|
|
||||||
self.data.as_mut().unwrap().insert(RouteData::new(data));
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -322,6 +322,7 @@ where
|
|||||||
default: self.default.clone(),
|
default: self.default.clone(),
|
||||||
services: Rc::new(
|
services: Rc::new(
|
||||||
cfg.into_services()
|
cfg.into_services()
|
||||||
|
.1
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(mut rdef, srv, guards, nested)| {
|
.map(|(mut rdef, srv, guards, nested)| {
|
||||||
rmap.add(&mut rdef, nested);
|
rmap.add(&mut rdef, nested);
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
use std::cell::{Ref, RefMut};
|
use std::cell::{Ref, RefMut};
|
||||||
|
use std::rc::Rc;
|
||||||
use std::{fmt, net};
|
use std::{fmt, net};
|
||||||
|
|
||||||
use actix_http::body::{Body, MessageBody, ResponseBody};
|
use actix_http::body::{Body, MessageBody, ResponseBody};
|
||||||
@ -180,12 +181,18 @@ impl ServiceRequest {
|
|||||||
/// Get an application data stored with `App::data()` method during
|
/// Get an application data stored with `App::data()` method during
|
||||||
/// application configuration.
|
/// application configuration.
|
||||||
pub fn app_data<T: 'static>(&self) -> Option<Data<T>> {
|
pub fn app_data<T: 'static>(&self) -> Option<Data<T>> {
|
||||||
if let Some(st) = self.req.app_config().extensions().get::<Data<T>>() {
|
if let Some(st) = self.req.0.app_data.get::<Data<T>>() {
|
||||||
Some(st.clone())
|
Some(st.clone())
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
/// Set new app data container
|
||||||
|
pub fn set_data_container(&mut self, extensions: Rc<Extensions>) {
|
||||||
|
Rc::get_mut(&mut self.req.0).unwrap().app_data = extensions;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Resource<Url> for ServiceRequest {
|
impl Resource<Url> for ServiceRequest {
|
||||||
|
42
src/test.rs
42
src/test.rs
@ -2,11 +2,10 @@
|
|||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use actix_http::cookie::Cookie;
|
|
||||||
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
|
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
|
||||||
use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
|
use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
|
||||||
use actix_http::test::TestRequest as HttpTestRequest;
|
use actix_http::test::TestRequest as HttpTestRequest;
|
||||||
use actix_http::{Extensions, Request};
|
use actix_http::{cookie::Cookie, Extensions, Request};
|
||||||
use actix_router::{Path, ResourceDef, Url};
|
use actix_router::{Path, ResourceDef, Url};
|
||||||
use actix_rt::Runtime;
|
use actix_rt::Runtime;
|
||||||
use actix_server_config::ServerConfig;
|
use actix_server_config::ServerConfig;
|
||||||
@ -20,7 +19,7 @@ use serde_json;
|
|||||||
pub use actix_http::test::TestBuffer;
|
pub use actix_http::test::TestBuffer;
|
||||||
|
|
||||||
use crate::config::{AppConfig, AppConfigInner};
|
use crate::config::{AppConfig, AppConfigInner};
|
||||||
use crate::data::{Data, RouteData};
|
use crate::data::Data;
|
||||||
use crate::dev::{Body, MessageBody, Payload};
|
use crate::dev::{Body, MessageBody, Payload};
|
||||||
use crate::request::HttpRequestPool;
|
use crate::request::HttpRequestPool;
|
||||||
use crate::rmap::ResourceMap;
|
use crate::rmap::ResourceMap;
|
||||||
@ -363,8 +362,8 @@ pub struct TestRequest {
|
|||||||
req: HttpTestRequest,
|
req: HttpTestRequest,
|
||||||
rmap: ResourceMap,
|
rmap: ResourceMap,
|
||||||
config: AppConfigInner,
|
config: AppConfigInner,
|
||||||
route_data: Extensions,
|
|
||||||
path: Path<Url>,
|
path: Path<Url>,
|
||||||
|
app_data: Extensions,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for TestRequest {
|
impl Default for TestRequest {
|
||||||
@ -373,8 +372,8 @@ impl Default for TestRequest {
|
|||||||
req: HttpTestRequest::default(),
|
req: HttpTestRequest::default(),
|
||||||
rmap: ResourceMap::new(ResourceDef::new("")),
|
rmap: ResourceMap::new(ResourceDef::new("")),
|
||||||
config: AppConfigInner::default(),
|
config: AppConfigInner::default(),
|
||||||
route_data: Extensions::new(),
|
|
||||||
path: Path::new(Url::new(Uri::default())),
|
path: Path::new(Url::new(Uri::default())),
|
||||||
|
app_data: Extensions::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -479,15 +478,8 @@ impl TestRequest {
|
|||||||
|
|
||||||
/// Set application data. This is equivalent of `App::data()` method
|
/// Set application data. This is equivalent of `App::data()` method
|
||||||
/// for testing purpose.
|
/// for testing purpose.
|
||||||
pub fn app_data<T: 'static>(self, data: T) -> Self {
|
pub fn data<T: 'static>(mut self, data: T) -> Self {
|
||||||
self.config.extensions.borrow_mut().insert(Data::new(data));
|
self.app_data.insert(Data::new(data));
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set route data. This is equivalent of `Route::data()` method
|
|
||||||
/// for testing purpose.
|
|
||||||
pub fn route_data<T: 'static>(mut self, data: T) -> Self {
|
|
||||||
self.route_data.insert(RouteData::new(data));
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -513,6 +505,7 @@ impl TestRequest {
|
|||||||
head,
|
head,
|
||||||
Rc::new(self.rmap),
|
Rc::new(self.rmap),
|
||||||
AppConfig::new(self.config),
|
AppConfig::new(self.config),
|
||||||
|
Rc::new(self.app_data),
|
||||||
HttpRequestPool::create(),
|
HttpRequestPool::create(),
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -529,15 +522,14 @@ impl TestRequest {
|
|||||||
let (head, _) = self.req.finish().into_parts();
|
let (head, _) = self.req.finish().into_parts();
|
||||||
self.path.get_mut().update(&head.uri);
|
self.path.get_mut().update(&head.uri);
|
||||||
|
|
||||||
let mut req = HttpRequest::new(
|
HttpRequest::new(
|
||||||
self.path,
|
self.path,
|
||||||
head,
|
head,
|
||||||
Rc::new(self.rmap),
|
Rc::new(self.rmap),
|
||||||
AppConfig::new(self.config),
|
AppConfig::new(self.config),
|
||||||
|
Rc::new(self.app_data),
|
||||||
HttpRequestPool::create(),
|
HttpRequestPool::create(),
|
||||||
);
|
)
|
||||||
req.set_route_data(Some(Rc::new(self.route_data)));
|
|
||||||
req
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
||||||
@ -545,14 +537,15 @@ impl TestRequest {
|
|||||||
let (head, payload) = self.req.finish().into_parts();
|
let (head, payload) = self.req.finish().into_parts();
|
||||||
self.path.get_mut().update(&head.uri);
|
self.path.get_mut().update(&head.uri);
|
||||||
|
|
||||||
let mut req = HttpRequest::new(
|
let req = HttpRequest::new(
|
||||||
self.path,
|
self.path,
|
||||||
head,
|
head,
|
||||||
Rc::new(self.rmap),
|
Rc::new(self.rmap),
|
||||||
AppConfig::new(self.config),
|
AppConfig::new(self.config),
|
||||||
|
Rc::new(self.app_data),
|
||||||
HttpRequestPool::create(),
|
HttpRequestPool::create(),
|
||||||
);
|
);
|
||||||
req.set_route_data(Some(Rc::new(self.route_data)));
|
|
||||||
(req, payload)
|
(req, payload)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -571,15 +564,20 @@ mod tests {
|
|||||||
.version(Version::HTTP_2)
|
.version(Version::HTTP_2)
|
||||||
.set(header::Date(SystemTime::now().into()))
|
.set(header::Date(SystemTime::now().into()))
|
||||||
.param("test", "123")
|
.param("test", "123")
|
||||||
.app_data(10u32)
|
.data(10u32)
|
||||||
.to_http_request();
|
.to_http_request();
|
||||||
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
||||||
assert!(req.headers().contains_key(header::DATE));
|
assert!(req.headers().contains_key(header::DATE));
|
||||||
assert_eq!(&req.match_info()["test"], "123");
|
assert_eq!(&req.match_info()["test"], "123");
|
||||||
assert_eq!(req.version(), Version::HTTP_2);
|
assert_eq!(req.version(), Version::HTTP_2);
|
||||||
let data = req.app_data::<u32>().unwrap();
|
let data = req.get_app_data::<u32>().unwrap();
|
||||||
|
assert!(req.get_app_data::<u64>().is_none());
|
||||||
assert_eq!(*data, 10);
|
assert_eq!(*data, 10);
|
||||||
assert_eq!(*data.get_ref(), 10);
|
assert_eq!(*data.get_ref(), 10);
|
||||||
|
|
||||||
|
assert!(req.app_data::<u64>().is_none());
|
||||||
|
let data = req.app_data::<u32>().unwrap();
|
||||||
|
assert_eq!(*data, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -81,7 +81,7 @@ where
|
|||||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
let req2 = req.clone();
|
let req2 = req.clone();
|
||||||
let (limit, err) = req
|
let (limit, err) = req
|
||||||
.route_data::<FormConfig>()
|
.app_data::<FormConfig>()
|
||||||
.map(|c| (c.limit, c.ehandler.clone()))
|
.map(|c| (c.limit, c.ehandler.clone()))
|
||||||
.unwrap_or((16384, None));
|
.unwrap_or((16384, None));
|
||||||
|
|
||||||
@ -132,12 +132,11 @@ impl<T: fmt::Display> fmt::Display for Form<T> {
|
|||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/index.html")
|
/// web::resource("/index.html")
|
||||||
/// .route(web::get()
|
|
||||||
/// // change `Form` extractor configuration
|
/// // change `Form` extractor configuration
|
||||||
/// .data(
|
/// .data(
|
||||||
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
|
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
|
||||||
/// )
|
/// )
|
||||||
/// .to(index))
|
/// .route(web::get().to(index))
|
||||||
/// );
|
/// );
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -176,7 +176,7 @@ where
|
|||||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||||
let req2 = req.clone();
|
let req2 = req.clone();
|
||||||
let (limit, err) = req
|
let (limit, err) = req
|
||||||
.route_data::<JsonConfig>()
|
.app_data::<JsonConfig>()
|
||||||
.map(|c| (c.limit, c.ehandler.clone()))
|
.map(|c| (c.limit, c.ehandler.clone()))
|
||||||
.unwrap_or((32768, None));
|
.unwrap_or((32768, None));
|
||||||
|
|
||||||
@ -220,8 +220,7 @@ where
|
|||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/index.html").route(
|
/// web::resource("/index.html").data(
|
||||||
/// web::post().data(
|
|
||||||
/// // change json extractor configuration
|
/// // change json extractor configuration
|
||||||
/// web::Json::<Info>::configure(|cfg| {
|
/// web::Json::<Info>::configure(|cfg| {
|
||||||
/// cfg.limit(4096)
|
/// cfg.limit(4096)
|
||||||
@ -230,7 +229,7 @@ where
|
|||||||
/// err, HttpResponse::Conflict().finish()).into()
|
/// err, HttpResponse::Conflict().finish()).into()
|
||||||
/// })
|
/// })
|
||||||
/// }))
|
/// }))
|
||||||
/// .to(index))
|
/// .route(web::post().to(index))
|
||||||
/// );
|
/// );
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@ -431,7 +430,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.route_data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
.data(JsonConfig::default().limit(10).error_handler(|err, _| {
|
||||||
let msg = MyObject {
|
let msg = MyObject {
|
||||||
name: "invalid request".to_string(),
|
name: "invalid request".to_string(),
|
||||||
};
|
};
|
||||||
@ -483,7 +482,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.route_data(JsonConfig::default().limit(10))
|
.data(JsonConfig::default().limit(10))
|
||||||
.to_http_parts();
|
.to_http_parts();
|
||||||
|
|
||||||
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
|
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
|
||||||
@ -500,7 +499,7 @@ mod tests {
|
|||||||
header::HeaderValue::from_static("16"),
|
header::HeaderValue::from_static("16"),
|
||||||
)
|
)
|
||||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||||
.route_data(
|
.data(
|
||||||
JsonConfig::default()
|
JsonConfig::default()
|
||||||
.limit(10)
|
.limit(10)
|
||||||
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
|
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
|
||||||
|
@ -130,7 +130,7 @@ impl FromRequest for Bytes {
|
|||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
||||||
let mut tmp;
|
let mut tmp;
|
||||||
let cfg = if let Some(cfg) = req.route_data::<PayloadConfig>() {
|
let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() {
|
||||||
cfg
|
cfg
|
||||||
} else {
|
} else {
|
||||||
tmp = PayloadConfig::default();
|
tmp = PayloadConfig::default();
|
||||||
@ -167,12 +167,11 @@ impl FromRequest for Bytes {
|
|||||||
///
|
///
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// let app = App::new().service(
|
/// let app = App::new().service(
|
||||||
/// web::resource("/index.html").route(
|
/// web::resource("/index.html")
|
||||||
/// web::get()
|
|
||||||
/// .data(String::configure(|cfg| { // <- limit size of the payload
|
/// .data(String::configure(|cfg| { // <- limit size of the payload
|
||||||
/// cfg.limit(4096)
|
/// cfg.limit(4096)
|
||||||
/// }))
|
/// }))
|
||||||
/// .to(index)) // <- register handler with extractor params
|
/// .route(web::get().to(index)) // <- register handler with extractor params
|
||||||
/// );
|
/// );
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@ -185,7 +184,7 @@ impl FromRequest for String {
|
|||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
||||||
let mut tmp;
|
let mut tmp;
|
||||||
let cfg = if let Some(cfg) = req.route_data::<PayloadConfig>() {
|
let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() {
|
||||||
cfg
|
cfg
|
||||||
} else {
|
} else {
|
||||||
tmp = PayloadConfig::default();
|
tmp = PayloadConfig::default();
|
||||||
|
@ -15,7 +15,7 @@ use crate::scope::Scope;
|
|||||||
use crate::service::WebService;
|
use crate::service::WebService;
|
||||||
|
|
||||||
pub use crate::config::ServiceConfig;
|
pub use crate::config::ServiceConfig;
|
||||||
pub use crate::data::{Data, RouteData};
|
pub use crate::data::Data;
|
||||||
pub use crate::request::HttpRequest;
|
pub use crate::request::HttpRequest;
|
||||||
pub use crate::types::*;
|
pub use crate::types::*;
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user