diff --git a/CHANGES.md b/CHANGES.md index bf60787f..f7693e66 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,15 @@ # Changes +## [1.0.0-alpha.6] - 2019-04-xx + +### Changed + +* Remove generic type for request payload, always use default. + +* Removed `Decompress` middleware. Bytes, String, Json, Form extractors + automatically decompress payload. + + ## [1.0.0-alpha.5] - 2019-04-12 ### Added diff --git a/actix-files/src/lib.rs b/actix-files/src/lib.rs index 6ebf4336..fd7ac3f6 100644 --- a/actix-files/src/lib.rs +++ b/actix-files/src/lib.rs @@ -32,9 +32,8 @@ use self::error::{FilesError, UriSegmentError}; pub use crate::named::NamedFile; pub use crate::range::HttpRange; -type HttpService

= BoxedService, ServiceResponse, Error>; -type HttpNewService

= - BoxedNewService<(), ServiceRequest

, ServiceResponse, Error, ()>; +type HttpService = BoxedService; +type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; /// Return the MIME type associated with a filename extension (case-insensitive). /// If `ext` is empty or no associated type for the extension was found, returns @@ -225,18 +224,18 @@ type MimeOverride = Fn(&mime::Name) -> DispositionType; /// .service(fs::Files::new("/static", ".")); /// } /// ``` -pub struct Files { +pub struct Files { path: String, directory: PathBuf, index: Option, show_index: bool, - default: Rc>>>>, + default: Rc>>>, renderer: Rc, mime_override: Option>, file_flags: named::Flags, } -impl Clone for Files { +impl Clone for Files { fn clone(&self) -> Self { Self { directory: self.directory.clone(), @@ -251,13 +250,13 @@ impl Clone for Files { } } -impl Files { +impl Files { /// Create new `Files` instance for specified base directory. /// /// `File` uses `ThreadPool` for blocking filesystem operations. /// By default pool with 5x threads of available cpus is used. /// Pool size can be changed by setting ACTIX_CPU_POOL environment variable. - pub fn new>(path: &str, dir: T) -> Files { + pub fn new>(path: &str, dir: T) -> Files { let dir = dir.into().canonicalize().unwrap_or_else(|_| PathBuf::new()); if !dir.is_dir() { log::error!("Specified path is not a directory"); @@ -335,7 +334,7 @@ impl Files { where F: IntoNewService, U: NewService< - Request = ServiceRequest, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, > + 'static, @@ -349,11 +348,8 @@ impl Files { } } -impl

HttpServiceFactory

for Files

-where - P: 'static, -{ - fn register(self, config: &mut ServiceConfig

) { +impl HttpServiceFactory for Files { + fn register(self, config: &mut ServiceConfig) { if self.default.borrow().is_none() { *self.default.borrow_mut() = Some(config.default_service()); } @@ -366,11 +362,11 @@ where } } -impl NewService for Files

{ - type Request = ServiceRequest

; +impl NewService for Files { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; - type Service = FilesService

; + type Service = FilesService; type InitError = (); type Future = Box>; @@ -401,22 +397,22 @@ impl NewService for Files

{ } } -pub struct FilesService

{ +pub struct FilesService { directory: PathBuf, index: Option, show_index: bool, - default: Option>, + default: Option, renderer: Rc, mime_override: Option>, file_flags: named::Flags, } -impl

FilesService

{ +impl FilesService { fn handle_err( &mut self, e: io::Error, req: HttpRequest, - payload: Payload

, + payload: Payload, ) -> Either< FutureResult, Box>, @@ -430,8 +426,8 @@ impl

FilesService

{ } } -impl

Service for FilesService

{ - type Request = ServiceRequest

; +impl Service for FilesService { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = Either< @@ -443,7 +439,7 @@ impl

Service for FilesService

{ Ok(Async::Ready(())) } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { let (req, pl) = req.into_parts(); let real_path = match PathBufWrp::get_pathbuf(req.match_info().path()) { @@ -547,11 +543,11 @@ impl PathBufWrp { } } -impl

FromRequest

for PathBufWrp { +impl FromRequest for PathBufWrp { type Error = UriSegmentError; type Future = Result; - fn from_request(req: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { PathBufWrp::get_pathbuf(req.match_info().path()) } } @@ -570,6 +566,7 @@ mod tests { self, ContentDisposition, DispositionParam, DispositionType, }; use actix_web::http::{Method, StatusCode}; + use actix_web::middleware::Compress; use actix_web::test::{self, TestRequest}; use actix_web::App; @@ -965,7 +962,7 @@ mod tests { #[test] fn test_named_file_content_encoding() { - let mut srv = test::init_service(App::new().enable_encoding().service( + let mut srv = test::init_service(App::new().wrap(Compress::default()).service( web::resource("/").to(|| { NamedFile::open("Cargo.toml") .unwrap() @@ -984,7 +981,7 @@ mod tests { #[test] fn test_named_file_content_encoding_gzip() { - let mut srv = test::init_service(App::new().enable_encoding().service( + let mut srv = test::init_service(App::new().wrap(Compress::default()).service( web::resource("/").to(|| { NamedFile::open("Cargo.toml") .unwrap() @@ -1053,15 +1050,15 @@ mod tests { #[test] fn test_static_files_bad_directory() { - let _st: Files<()> = Files::new("/", "missing"); - let _st: Files<()> = Files::new("/", "Cargo.toml"); + let _st: Files = Files::new("/", "missing"); + let _st: Files = Files::new("/", "Cargo.toml"); } #[test] fn test_default_handler_file_missing() { let mut st = test::block_on( Files::new("/", ".") - .default_handler(|req: ServiceRequest<_>| { + .default_handler(|req: ServiceRequest| { Ok(req.into_response(HttpResponse::Ok().body("default content"))) }) .new_service(&()), diff --git a/actix-files/src/named.rs b/actix-files/src/named.rs index 1f54c828..c506c02f 100644 --- a/actix-files/src/named.rs +++ b/actix-files/src/named.rs @@ -15,7 +15,7 @@ use actix_web::http::header::{ self, ContentDisposition, DispositionParam, DispositionType, }; use actix_web::http::{ContentEncoding, Method, StatusCode}; -use actix_web::middleware::encoding::BodyEncoding; +use actix_web::middleware::BodyEncoding; use actix_web::{Error, HttpMessage, HttpRequest, HttpResponse, Responder}; use crate::range::HttpRange; diff --git a/actix-http/src/payload.rs b/actix-http/src/payload.rs index 91e6b5c9..0ce20970 100644 --- a/actix-http/src/payload.rs +++ b/actix-http/src/payload.rs @@ -53,6 +53,7 @@ where type Item = Bytes; type Error = PayloadError; + #[inline] fn poll(&mut self) -> Poll, Self::Error> { match self { Payload::None => Ok(Async::Ready(None)), diff --git a/actix-multipart/src/extractor.rs b/actix-multipart/src/extractor.rs index 52290b60..1f2f15c6 100644 --- a/actix-multipart/src/extractor.rs +++ b/actix-multipart/src/extractor.rs @@ -1,9 +1,5 @@ //! Multipart payload support -use bytes::Bytes; -use futures::Stream; - -use actix_web::error::{Error, PayloadError}; -use actix_web::{dev::Payload, FromRequest, HttpRequest}; +use actix_web::{dev::Payload, Error, FromRequest, HttpRequest}; use crate::server::Multipart; @@ -34,15 +30,12 @@ use crate::server::Multipart; /// } /// # fn main() {} /// ``` -impl

FromRequest

for Multipart -where - P: Stream + 'static, -{ +impl FromRequest for Multipart { type Error = Error; type Future = Result; #[inline] - fn from_request(req: &HttpRequest, payload: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { Ok(Multipart::new(req.headers(), payload.take())) } } diff --git a/actix-session/src/cookie.rs b/actix-session/src/cookie.rs index b44c87e0..634288b4 100644 --- a/actix-session/src/cookie.rs +++ b/actix-session/src/cookie.rs @@ -120,7 +120,7 @@ impl CookieSessionInner { Ok(()) } - fn load

(&self, req: &ServiceRequest

) -> HashMap { + fn load(&self, req: &ServiceRequest) -> HashMap { if let Ok(cookies) = req.cookies() { for cookie in cookies.iter() { if cookie.name() == self.name { @@ -256,13 +256,13 @@ impl CookieSession { } } -impl Transform for CookieSession +impl Transform for CookieSession where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, S::Error: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type InitError = (); @@ -283,13 +283,13 @@ pub struct CookieSessionMiddleware { inner: Rc, } -impl Service for CookieSessionMiddleware +impl Service for CookieSessionMiddleware where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, S::Error: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type Future = Box>; @@ -298,7 +298,7 @@ where self.service.poll_ready() } - fn call(&mut self, mut req: ServiceRequest

) -> Self::Future { + fn call(&mut self, mut req: ServiceRequest) -> Self::Future { let inner = self.inner.clone(); let state = self.inner.load(&req); Session::set_session(state.into_iter(), &mut req); diff --git a/actix-session/src/lib.rs b/actix-session/src/lib.rs index 4b7ae2fd..8db87523 100644 --- a/actix-session/src/lib.rs +++ b/actix-session/src/lib.rs @@ -119,9 +119,9 @@ impl Session { inner.state.clear() } - pub fn set_session

( + pub fn set_session( data: impl Iterator, - req: &mut ServiceRequest

, + req: &mut ServiceRequest, ) { let session = Session::get_session(&mut *req.extensions_mut()); let mut inner = session.0.borrow_mut(); @@ -172,12 +172,12 @@ impl Session { /// } /// # fn main() {} /// ``` -impl

FromRequest

for Session { +impl FromRequest for Session { type Error = Error; type Future = Result; #[inline] - fn from_request(req: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { Ok(Session::get_session(&mut *req.extensions_mut())) } } diff --git a/actix-web-codegen/src/route.rs b/actix-web-codegen/src/route.rs index e1a870db..348ce86a 100644 --- a/actix-web-codegen/src/route.rs +++ b/actix-web-codegen/src/route.rs @@ -61,8 +61,8 @@ impl fmt::Display for Args { #[allow(non_camel_case_types)] pub struct {name}; -impl actix_web::dev::HttpServiceFactory

for {name} {{ - fn register(self, config: &mut actix_web::dev::ServiceConfig

) {{ +impl actix_web::dev::HttpServiceFactory for {name} {{ + fn register(self, config: &mut actix_web::dev::ServiceConfig) {{ {ast} let resource = actix_web::Resource::new(\"{path}\"){guards}.{to}({name}); diff --git a/actix-web-codegen/tests/test_macro.rs b/actix-web-codegen/tests/test_macro.rs index c27eefde..dd105785 100644 --- a/actix-web-codegen/tests/test_macro.rs +++ b/actix-web-codegen/tests/test_macro.rs @@ -4,11 +4,6 @@ use actix_web::{http, App, HttpResponse, Responder}; use actix_web_codegen::get; use futures::{future, Future}; -//fn guard_head(head: &actix_web::dev::RequestHead) -> bool { -// true -//} - -//#[get("/test", guard="guard_head")] #[get("/test")] fn test() -> impl Responder { HttpResponse::Ok() diff --git a/examples/basic.rs b/examples/basic.rs index 1191b371..91119657 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -27,7 +27,7 @@ fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2")) - .wrap(middleware::encoding::Compress::default()) + .wrap(middleware::Compress::default()) .wrap(middleware::Logger::default()) .service(index) .service(no_params) diff --git a/src/app.rs b/src/app.rs index f378572b..39c96cd9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -3,22 +3,18 @@ use std::marker::PhantomData; use std::rc::Rc; use actix_http::body::{Body, MessageBody}; -#[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] -use actix_http::encoding::{Decoder, Encoder}; use actix_server_config::ServerConfig; use actix_service::boxed::{self, BoxedNewService}; use actix_service::{ apply_transform, IntoNewService, IntoTransform, NewService, Transform, }; -#[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] -use bytes::Bytes; -use futures::{IntoFuture, Stream}; +use futures::IntoFuture; -use crate::app_service::{AppChain, AppEntry, AppInit, AppRouting, AppRoutingFactory}; +use crate::app_service::{AppEntry, AppInit, AppRoutingFactory}; use crate::config::{AppConfig, AppConfigInner, RouterConfig}; use crate::data::{Data, DataFactory}; -use crate::dev::{Payload, PayloadStream, ResourceDef}; -use crate::error::{Error, PayloadError}; +use crate::dev::ResourceDef; +use crate::error::Error; use crate::resource::Resource; use crate::route::Route; use crate::service::{ @@ -26,40 +22,44 @@ use crate::service::{ ServiceResponse, }; -type HttpNewService

= - BoxedNewService<(), ServiceRequest

, ServiceResponse, Error, ()>; +type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; /// Application builder - structure that follows the builder pattern /// for building application instances. -pub struct App -where - T: NewService, Response = ServiceRequest>, -{ - chain: T, +pub struct App { + endpoint: T, + services: Vec>, + default: Option>, + factory_ref: Rc>>, data: Vec>, config: AppConfigInner, - _t: PhantomData<(In, Out)>, + external: Vec, + _t: PhantomData<(B)>, } -impl App { +impl App { /// Create application builder. Application can be configured with a builder-like pattern. pub fn new() -> Self { + let fref = Rc::new(RefCell::new(None)); App { - chain: AppChain, + endpoint: AppEntry::new(fref.clone()), data: Vec::new(), + services: Vec::new(), + default: None, + factory_ref: fref, config: AppConfigInner::default(), + external: Vec::new(), _t: PhantomData, } } } -impl App +impl App where - In: 'static, - Out: 'static, + B: MessageBody, T: NewService< - Request = ServiceRequest, - Response = ServiceRequest, + Request = ServiceRequest, + Response = ServiceResponse, Error = Error, InitError = (), >, @@ -112,151 +112,6 @@ where self } - /// Registers middleware, in the form of a middleware component (type), - /// that runs during inbound and/or outbound processing in the request - /// lifecycle (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 futures::Future; - /// use actix_web::{middleware, web, App}; - /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; - /// - /// fn index() -> &'static str { - /// "Welcome!" - /// } - /// - /// fn main() { - /// let app = App::new() - /// .wrap(middleware::Logger::default()) - /// .route("/index.html", web::get().to(index)); - /// } - /// ``` - pub fn wrap( - self, - mw: F, - ) -> AppRouter< - T, - Out, - B, - impl NewService< - Request = ServiceRequest, - Response = ServiceResponse, - Error = Error, - InitError = (), - >, - > - where - M: Transform< - AppRouting, - Request = ServiceRequest, - Response = ServiceResponse, - Error = Error, - InitError = (), - >, - F: IntoTransform>, - { - let fref = Rc::new(RefCell::new(None)); - let endpoint = apply_transform(mw, AppEntry::new(fref.clone())); - AppRouter { - endpoint, - chain: self.chain, - data: self.data, - services: Vec::new(), - default: None, - factory_ref: fref, - config: self.config, - external: Vec::new(), - _t: PhantomData, - } - } - - /// Registers middleware, in the form of a closure, that runs during inbound - /// and/or outbound processing in the request lifecycle (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 futures::Future; - /// use actix_web::{web, App}; - /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; - /// - /// fn index() -> &'static str { - /// "Welcome!" - /// } - /// - /// fn main() { - /// let app = App::new() - /// .wrap_fn(|req, srv| - /// srv.call(req).map(|mut res| { - /// res.headers_mut().insert( - /// CONTENT_TYPE, HeaderValue::from_static("text/plain"), - /// ); - /// res - /// })) - /// .route("/index.html", web::get().to(index)); - /// } - /// ``` - pub fn wrap_fn( - self, - mw: F, - ) -> AppRouter< - T, - Out, - B, - impl NewService< - Request = ServiceRequest, - Response = ServiceResponse, - Error = Error, - InitError = (), - >, - > - where - F: FnMut(ServiceRequest, &mut AppRouting) -> R + Clone, - R: IntoFuture, Error = Error>, - { - self.wrap(mw) - } - - /// Register a request modifier. It can modify any request parameters - /// including request payload type. - pub fn chain( - self, - chain: F, - ) -> App< - In, - P, - impl NewService< - Request = ServiceRequest, - Response = ServiceRequest

, - Error = Error, - InitError = (), - >, - > - where - C: NewService< - Request = ServiceRequest, - Response = ServiceRequest

, - Error = Error, - InitError = (), - >, - F: IntoNewService, - { - let chain = self.chain.and_then(chain.into_new_service()); - App { - chain, - data: self.data, - config: self.config, - _t: PhantomData, - } - } - /// Run external configuration as part of the application building /// process /// @@ -269,7 +124,7 @@ where /// use actix_web::{web, middleware, App, HttpResponse}; /// /// // this function could be located in different module - /// fn config

(cfg: &mut web::RouterConfig

) { + /// fn config(cfg: &mut web::RouterConfig) { /// cfg.service(web::resource("/test") /// .route(web::get().to(|| HttpResponse::Ok())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) @@ -283,27 +138,16 @@ where /// .route("/index.html", web::get().to(|| HttpResponse::Ok())); /// } /// ``` - pub fn configure(mut self, f: F) -> AppRouter> + pub fn configure(mut self, f: F) -> Self where - F: Fn(&mut RouterConfig), + F: Fn(&mut RouterConfig), { let mut cfg = RouterConfig::new(); f(&mut cfg); self.data.extend(cfg.data); - - 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: cfg.services, - external: cfg.external, - _t: PhantomData, - } + self.services.extend(cfg.services); + self.external.extend(cfg.external); + self } /// Configure route for a specific path. @@ -325,171 +169,7 @@ where /// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed())); /// } /// ``` - pub fn route( - self, - path: &str, - mut route: Route, - ) -> AppRouter> { - 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(self, service: F) -> AppRouter> - where - F: HttpServiceFactory + '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 - } - - #[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] - /// Enable content compression and decompression. - pub fn enable_encoding( - self, - ) -> AppRouter< - impl NewService< - Request = ServiceRequest, - Response = ServiceRequest>>, - Error = Error, - InitError = (), - >, - Decoder>, - Encoder, - impl NewService< - Request = ServiceRequest>>, - Response = ServiceResponse>, - Error = Error, - InitError = (), - >, - > - where - Out: Stream, - { - use crate::middleware::encoding::{Compress, Decompress}; - - self.chain(Decompress::new()).wrap(Compress::default()) - } -} - -/// Application router builder - Structure that follows the builder pattern -/// for building application instances. -pub struct AppRouter { - chain: C, - endpoint: T, - services: Vec>>, - default: Option>>, - factory_ref: Rc>>>, - data: Vec>, - config: AppConfigInner, - external: Vec, - _t: PhantomData<(P, B)>, -} - -impl AppRouter -where - P: 'static, - B: MessageBody, - T: NewService< - Request = ServiceRequest

, - Response = ServiceResponse, - Error = Error, - InitError = (), - >, -{ - /// 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 - /// # extern crate actix_web; - /// use actix_web::{web, middleware, App, HttpResponse}; - /// - /// // this function could be located in different module - /// fn config

(cfg: &mut web::RouterConfig

) { - /// cfg.service(web::resource("/test") - /// .route(web::get().to(|| HttpResponse::Ok())) - /// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) - /// ); - /// } - /// - /// fn main() { - /// let app = App::new() - /// .wrap(middleware::Logger::default()) - /// .configure(config) // <- register resources - /// .route("/index.html", web::get().to(|| HttpResponse::Ok())); - /// } - /// ``` - pub fn configure(mut self, f: F) -> Self - where - F: Fn(&mut RouterConfig

), - { - let mut cfg = RouterConfig::new(); - f(&mut cfg); - self.data.extend(cfg.data); - self.services.extend(cfg.services); - self.external.extend(cfg.external); - - self - } - - /// 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 { + pub fn route(self, path: &str, mut route: Route) -> Self { self.service( Resource::new(path) .add_guards(route.take_guards()) @@ -508,94 +188,31 @@ where /// * "StaticFiles" is a service for static files support pub fn service(mut self, factory: F) -> Self where - F: HttpServiceFactory

+ 'static, + F: HttpServiceFactory + 'static, { self.services .push(Box::new(ServiceFactoryWrapper::new(factory))); self } - /// Registers middleware, in the form of a middleware component (type), - /// that runs during inbound and/or outbound processing in the request - /// lifecycle (request -> response), modifying request/response as - /// necessary, across all requests managed by the *Route*. + /// Set server host name. /// - /// Use middleware when you need to read or modify *every* request or response in some way. + /// 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. /// - pub fn wrap( - self, - mw: F, - ) -> AppRouter< - C, - P, - B1, - impl NewService< - Request = ServiceRequest

, - Response = ServiceResponse, - Error = Error, - InitError = (), - >, - > - where - M: Transform< - T::Service, - Request = ServiceRequest

, - Response = ServiceResponse, - Error = Error, - InitError = (), - >, - B1: MessageBody, - F: IntoTransform, - { - let endpoint = apply_transform(mw, self.endpoint); - AppRouter { - endpoint, - chain: self.chain, - data: self.data, - services: self.services, - default: self.default, - factory_ref: self.factory_ref, - config: self.config, - external: self.external, - _t: PhantomData, - } - } - - /// Registers middleware, in the form of a closure, that runs during inbound - /// and/or outbound processing in the request lifecycle (request -> response), - /// modifying request/response as necessary, across all requests managed by - /// the *Route*. - /// - /// Use middleware when you need to read or modify *every* request or response in some way. - /// - pub fn wrap_fn( - self, - mw: F, - ) -> AppRouter< - C, - P, - B1, - impl NewService< - Request = ServiceRequest

, - Response = ServiceResponse, - Error = Error, - InitError = (), - >, - > - where - B1: MessageBody, - F: FnMut(ServiceRequest

, &mut T::Service) -> R + Clone, - R: IntoFuture, Error = Error>, - { - self.wrap(mw) + /// 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 } /// Default resource to be used if no matching resource could be found. pub fn default_resource(mut self, f: F) -> Self where - F: FnOnce(Resource

) -> Resource, + F: FnOnce(Resource) -> Resource, U: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -641,27 +258,128 @@ where 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 + /// lifecycle (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 futures::Future; + /// use actix_web::{middleware, web, App}; + /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; + /// + /// fn index() -> &'static str { + /// "Welcome!" + /// } + /// + /// fn main() { + /// let app = App::new() + /// .wrap(middleware::Logger::default()) + /// .route("/index.html", web::get().to(index)); + /// } + /// ``` + pub fn wrap( + self, + mw: F, + ) -> App< + impl NewService< + Request = ServiceRequest, + Response = ServiceResponse, + Error = Error, + InitError = (), + >, + B1, + > + where + M: Transform< + T::Service, + Request = ServiceRequest, + Response = ServiceResponse, + Error = Error, + InitError = (), + >, + B1: MessageBody, + F: IntoTransform, + { + let endpoint = apply_transform(mw, self.endpoint); + App { + endpoint, + data: self.data, + services: self.services, + default: self.default, + factory_ref: self.factory_ref, + config: self.config, + external: self.external, + _t: PhantomData, + } + } + + /// Registers middleware, in the form of a closure, that runs during inbound + /// and/or outbound processing in the request lifecycle (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 futures::Future; + /// use actix_web::{web, App}; + /// use actix_web::http::{header::CONTENT_TYPE, HeaderValue}; + /// + /// fn index() -> &'static str { + /// "Welcome!" + /// } + /// + /// fn main() { + /// let app = App::new() + /// .wrap_fn(|req, srv| + /// srv.call(req).map(|mut res| { + /// res.headers_mut().insert( + /// CONTENT_TYPE, HeaderValue::from_static("text/plain"), + /// ); + /// res + /// })) + /// .route("/index.html", web::get().to(index)); + /// } + /// ``` + pub fn wrap_fn( + self, + mw: F, + ) -> App< + impl NewService< + Request = ServiceRequest, + Response = ServiceResponse, + Error = Error, + InitError = (), + >, + B1, + > + where + B1: MessageBody, + F: FnMut(ServiceRequest, &mut T::Service) -> R + Clone, + R: IntoFuture, Error = Error>, + { + self.wrap(mw) + } } -impl IntoNewService, ServerConfig> - for AppRouter +impl IntoNewService, ServerConfig> for App where + B: MessageBody, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), >, - C: NewService< - Request = ServiceRequest, - Response = ServiceRequest

, - Error = Error, - InitError = (), - >, { - fn into_new_service(self) -> AppInit { + fn into_new_service(self) -> AppInit { AppInit { - chain: self.chain, data: self.data, endpoint: self.endpoint, services: RefCell::new(self.services), @@ -742,13 +460,13 @@ mod tests { assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } - fn md( - req: ServiceRequest

, + fn md( + req: ServiceRequest, srv: &mut S, ) -> impl IntoFuture, Error = Error> where S: Service< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, >, diff --git a/src/app_service.rs b/src/app_service.rs index 593fbe67..a5d90636 100644 --- a/src/app_service.rs +++ b/src/app_service.rs @@ -6,7 +6,7 @@ use actix_http::{Request, Response}; use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url}; use actix_server_config::ServerConfig; use actix_service::boxed::{self, BoxedNewService, BoxedService}; -use actix_service::{fn_service, AndThen, NewService, Service, ServiceExt}; +use actix_service::{fn_service, NewService, Service}; use futures::future::{ok, Either, FutureResult}; use futures::{Async, Future, Poll}; @@ -19,9 +19,8 @@ use crate::rmap::ResourceMap; use crate::service::{ServiceFactory, ServiceRequest, ServiceResponse}; type Guards = Vec>; -type HttpService

= BoxedService, ServiceResponse, Error>; -type HttpNewService

= - BoxedNewService<(), ServiceRequest

, ServiceResponse, Error, ()>; +type HttpService = BoxedService; +type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type BoxedResponse = Either< FutureResult, Box>, @@ -29,36 +28,28 @@ type BoxedResponse = Either< /// Service factory to convert `Request` to a `ServiceRequest`. /// It also executes data factories. -pub struct AppInit +pub struct AppInit where - C: NewService>, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), >, { - pub(crate) chain: C, pub(crate) endpoint: T, pub(crate) data: Vec>, pub(crate) config: RefCell, - pub(crate) services: RefCell>>>, - pub(crate) default: Option>>, - pub(crate) factory_ref: Rc>>>, + pub(crate) services: RefCell>>, + pub(crate) default: Option>, + pub(crate) factory_ref: Rc>>, pub(crate) external: RefCell>, } -impl NewService for AppInit +impl NewService for AppInit where - C: NewService< - Request = ServiceRequest, - Response = ServiceRequest

, - Error = Error, - InitError = (), - >, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -66,15 +57,15 @@ where { type Request = Request; type Response = ServiceResponse; - type Error = C::Error; - type InitError = C::InitError; - type Service = AndThen, T::Service>; - type Future = AppInitResult; + type Error = T::Error; + type InitError = T::InitError; + type Service = AppInitService; + type Future = AppInitResult; fn new_service(&self, cfg: &ServerConfig) -> Self::Future { // update resource default service let default = self.default.clone().unwrap_or_else(|| { - Rc::new(boxed::new_service(fn_service(|req: ServiceRequest

| { + Rc::new(boxed::new_service(fn_service(|req: ServiceRequest| { Ok(req.into_response(Response::NotFound().finish())) }))) }); @@ -121,8 +112,6 @@ where rmap.finish(rmap.clone()); AppInitResult { - chain: None, - chain_fut: self.chain.new_service(&()), endpoint: None, endpoint_fut: self.endpoint.new_service(&()), data: self.data.iter().map(|s| s.construct()).collect(), @@ -133,38 +122,29 @@ where } } -pub struct AppInitResult +pub struct AppInitResult where - C: NewService, T: NewService, { - chain: Option, endpoint: Option, - chain_fut: C::Future, endpoint_fut: T::Future, rmap: Rc, data: Vec>, config: AppConfig, - _t: PhantomData<(P, B)>, + _t: PhantomData, } -impl Future for AppInitResult +impl Future for AppInitResult where - C: NewService< - Request = ServiceRequest, - Response = ServiceRequest

, - Error = Error, - InitError = (), - >, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), >, { - type Item = AndThen, T::Service>; - type Error = C::InitError; + type Item = AppInitService; + type Error = T::InitError; fn poll(&mut self) -> Poll { let mut idx = 0; @@ -177,28 +157,19 @@ where } } - if self.chain.is_none() { - if let Async::Ready(srv) = self.chain_fut.poll()? { - self.chain = Some(srv); - } - } - if self.endpoint.is_none() { if let Async::Ready(srv) = self.endpoint_fut.poll()? { self.endpoint = Some(srv); } } - if self.chain.is_some() && self.endpoint.is_some() { - Ok(Async::Ready( - AppInitService { - chain: self.chain.take().unwrap(), - rmap: self.rmap.clone(), - config: self.config.clone(), - pool: HttpRequestPool::create(), - } - .and_then(self.endpoint.take().unwrap()), - )) + if self.endpoint.is_some() { + Ok(Async::Ready(AppInitService { + service: self.endpoint.take().unwrap(), + rmap: self.rmap.clone(), + config: self.config.clone(), + pool: HttpRequestPool::create(), + })) } else { Ok(Async::NotReady) } @@ -206,27 +177,27 @@ where } /// Service to convert `Request` to a `ServiceRequest` -pub struct AppInitService +pub struct AppInitService where - C: Service, Error = Error>, + T: Service, Error = Error>, { - chain: C, + service: T, rmap: Rc, config: AppConfig, pool: &'static HttpRequestPool, } -impl Service for AppInitService +impl Service for AppInitService where - C: Service, Error = Error>, + T: Service, Error = Error>, { type Request = Request; - type Response = ServiceRequest

; - type Error = C::Error; - type Future = C::Future; + type Response = ServiceResponse; + type Error = T::Error; + type Future = T::Future; fn poll_ready(&mut self) -> Poll<(), Self::Error> { - self.chain.poll_ready() + self.service.poll_ready() } fn call(&mut self, req: Request) -> Self::Future { @@ -247,22 +218,22 @@ where self.pool, ) }; - self.chain.call(ServiceRequest::from_parts(req, payload)) + self.service.call(ServiceRequest::from_parts(req, payload)) } } -pub struct AppRoutingFactory

{ - services: Rc, RefCell>)>>, - default: Rc>, +pub struct AppRoutingFactory { + services: Rc>)>>, + default: Rc, } -impl NewService for AppRoutingFactory

{ - type Request = ServiceRequest

; +impl NewService for AppRoutingFactory { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = AppRouting

; - type Future = AppRoutingFactoryResponse

; + type Service = AppRouting; + type Future = AppRoutingFactoryResponse; fn new_service(&self, _: &()) -> Self::Future { AppRoutingFactoryResponse { @@ -283,23 +254,23 @@ impl NewService for AppRoutingFactory

{ } } -type HttpServiceFut

= Box, Error = ()>>; +type HttpServiceFut = Box>; /// Create app service #[doc(hidden)] -pub struct AppRoutingFactoryResponse

{ - fut: Vec>, - default: Option>, - default_fut: Option, Error = ()>>>, +pub struct AppRoutingFactoryResponse { + fut: Vec, + default: Option, + default_fut: Option>>, } -enum CreateAppRoutingItem

{ - Future(Option, Option, HttpServiceFut

), - Service(ResourceDef, Option, HttpService

), +enum CreateAppRoutingItem { + Future(Option, Option, HttpServiceFut), + Service(ResourceDef, Option, HttpService), } -impl

Future for AppRoutingFactoryResponse

{ - type Item = AppRouting

; +impl Future for AppRoutingFactoryResponse { + type Item = AppRouting; type Error = (); fn poll(&mut self) -> Poll { @@ -360,14 +331,14 @@ impl

Future for AppRoutingFactoryResponse

{ } } -pub struct AppRouting

{ - router: Router, Guards>, - ready: Option<(ServiceRequest

, ResourceInfo)>, - default: Option>, +pub struct AppRouting { + router: Router, + ready: Option<(ServiceRequest, ResourceInfo)>, + default: Option, } -impl

Service for AppRouting

{ - type Request = ServiceRequest

; +impl Service for AppRouting { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = BoxedResponse; @@ -380,7 +351,7 @@ impl

Service for AppRouting

{ } } - fn call(&mut self, mut req: ServiceRequest

) -> Self::Future { + fn call(&mut self, mut req: ServiceRequest) -> Self::Future { let res = self.router.recognize_mut_checked(&mut req, |req, guards| { if let Some(ref guards) = guards { for f in guards { @@ -404,58 +375,25 @@ impl

Service for AppRouting

{ } /// Wrapper service for routing -pub struct AppEntry

{ - factory: Rc>>>, +pub struct AppEntry { + factory: Rc>>, } -impl

AppEntry

{ - pub fn new(factory: Rc>>>) -> Self { +impl AppEntry { + pub fn new(factory: Rc>>) -> Self { AppEntry { factory } } } -impl NewService for AppEntry

{ - type Request = ServiceRequest

; +impl NewService for AppEntry { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = AppRouting

; - type Future = AppRoutingFactoryResponse

; + type Service = AppRouting; + type Future = AppRoutingFactoryResponse; fn new_service(&self, _: &()) -> Self::Future { self.factory.borrow_mut().as_mut().unwrap().new_service(&()) } } - -#[doc(hidden)] -pub struct AppChain; - -impl NewService for AppChain { - type Request = ServiceRequest; - type Response = ServiceRequest; - type Error = Error; - type InitError = (); - type Service = AppChain; - type Future = FutureResult; - - fn new_service(&self, _: &()) -> Self::Future { - ok(AppChain) - } -} - -impl Service for AppChain { - type Request = ServiceRequest; - type Response = ServiceRequest; - type Error = Error; - type Future = FutureResult; - - #[inline] - fn poll_ready(&mut self) -> Poll<(), Self::Error> { - Ok(Async::Ready(())) - } - - #[inline] - fn call(&mut self, req: ServiceRequest) -> Self::Future { - ok(req) - } -} diff --git a/src/config.rs b/src/config.rs index 1e552291..c28b6678 100644 --- a/src/config.rs +++ b/src/config.rs @@ -19,25 +19,25 @@ use crate::service::{ }; type Guards = Vec>; -type HttpNewService

= - boxed::BoxedNewService<(), ServiceRequest

, ServiceResponse, Error, ()>; +type HttpNewService = + boxed::BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; /// Application configuration -pub struct ServiceConfig

{ +pub struct ServiceConfig { config: AppConfig, root: bool, - default: Rc>, + default: Rc, services: Vec<( ResourceDef, - HttpNewService

, + HttpNewService, Option, Option>, )>, } -impl ServiceConfig

{ +impl ServiceConfig { /// Crate server settings instance - pub(crate) fn new(config: AppConfig, default: Rc>) -> Self { + pub(crate) fn new(config: AppConfig, default: Rc) -> Self { ServiceConfig { config, default, @@ -55,7 +55,7 @@ impl ServiceConfig

{ self, ) -> Vec<( ResourceDef, - HttpNewService

, + HttpNewService, Option, Option>, )> { @@ -77,7 +77,7 @@ impl ServiceConfig

{ } /// Default resource - pub fn default_service(&self) -> Rc> { + pub fn default_service(&self) -> Rc { self.default.clone() } @@ -90,7 +90,7 @@ impl ServiceConfig

{ ) where F: IntoNewService, S: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -169,13 +169,13 @@ impl Default for AppConfigInner { /// Part of application configuration could be offloaded /// to set of external methods. This could help with /// modularization of big application configuration. -pub struct RouterConfig { - pub(crate) services: Vec>>, +pub struct RouterConfig { + pub(crate) services: Vec>, pub(crate) data: Vec>, pub(crate) external: Vec, } -impl RouterConfig

{ +impl RouterConfig { pub(crate) fn new() -> Self { Self { services: Vec::new(), @@ -211,7 +211,7 @@ impl RouterConfig

{ /// Configure route for a specific path. /// /// This is same as `App::route()` method. - pub fn route(&mut self, path: &str, mut route: Route

) -> &mut Self { + pub fn route(&mut self, path: &str, mut route: Route) -> &mut Self { self.service( Resource::new(path) .add_guards(route.take_guards()) @@ -224,7 +224,7 @@ impl RouterConfig

{ /// This is same as `App::service()` method. pub fn service(&mut self, factory: F) -> &mut Self where - F: HttpServiceFactory

+ 'static, + F: HttpServiceFactory + 'static, { self.services .push(Box::new(ServiceFactoryWrapper::new(factory))); @@ -261,7 +261,7 @@ mod tests { #[test] fn test_data() { - let cfg = |cfg: &mut RouterConfig<_>| { + let cfg = |cfg: &mut RouterConfig| { cfg.data(10usize); }; @@ -276,7 +276,7 @@ mod tests { #[test] fn test_data_factory() { - let cfg = |cfg: &mut RouterConfig<_>| { + let cfg = |cfg: &mut RouterConfig| { cfg.data_factory(|| Ok::<_, ()>(10usize)); }; @@ -288,7 +288,7 @@ mod tests { let resp = block_on(srv.call(req)).unwrap(); assert_eq!(resp.status(), StatusCode::OK); - let cfg2 = |cfg: &mut RouterConfig<_>| { + let cfg2 = |cfg: &mut RouterConfig| { cfg.data_factory(|| Ok::<_, ()>(10u32)); }; let mut srv = init_service( diff --git a/src/data.rs b/src/data.rs index d06eb646..d178d779 100644 --- a/src/data.rs +++ b/src/data.rs @@ -88,12 +88,12 @@ impl Clone for Data { } } -impl FromRequest

for Data { +impl FromRequest for Data { type Error = Error; type Future = Result; #[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::>() { Ok(st.clone()) } else { @@ -232,12 +232,12 @@ impl Clone for RouteData { } } -impl FromRequest

for RouteData { +impl FromRequest for RouteData { type Error = Error; type Future = Result; #[inline] - fn from_request(req: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { if let Some(st) = req.route_data::() { Ok(st.clone()) } else { diff --git a/src/extract.rs b/src/extract.rs index 73cbb4ce..3f20f3e3 100644 --- a/src/extract.rs +++ b/src/extract.rs @@ -10,7 +10,7 @@ use crate::request::HttpRequest; /// Trait implemented by types that can be extracted from request. /// /// Types that implement this trait can be used with `Route` handlers. -pub trait FromRequest

: Sized { +pub trait FromRequest: Sized { /// The associated error which can be returned. type Error: Into; @@ -18,7 +18,7 @@ pub trait FromRequest

: Sized { type Future: IntoFuture; /// Convert request to a Self - fn from_request(req: &HttpRequest, payload: &mut Payload

) -> Self::Future; + fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future; /// Convert request to a Self /// @@ -45,11 +45,11 @@ pub trait FromRequest

: Sized { /// name: String /// } /// -/// impl

FromRequest

for Thing { +/// impl FromRequest for Thing { /// type Error = Error; /// type Future = Result; /// -/// fn from_request(req: &HttpRequest, payload: &mut dev::Payload

) -> Self::Future { +/// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { /// if rand::random() { /// Ok(Thing { name: "thingy".into() }) /// } else { @@ -75,16 +75,16 @@ pub trait FromRequest

: Sized { /// ); /// } /// ``` -impl FromRequest

for Option +impl FromRequest for Option where - T: FromRequest

, + T: FromRequest, T::Future: 'static, { type Error = Error; type Future = Box, Error = Error>>; #[inline] - fn from_request(req: &HttpRequest, payload: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { Box::new( T::from_request(req, payload) .into_future() @@ -116,11 +116,11 @@ where /// name: String /// } /// -/// impl

FromRequest

for Thing { +/// impl FromRequest for Thing { /// type Error = Error; /// type Future = Result; /// -/// fn from_request(req: &HttpRequest, payload: &mut dev::Payload

) -> Self::Future { +/// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { /// if rand::random() { /// Ok(Thing { name: "thingy".into() }) /// } else { @@ -143,9 +143,9 @@ where /// ); /// } /// ``` -impl FromRequest

for Result +impl FromRequest for Result where - T: FromRequest

, + T: FromRequest, T::Future: 'static, T::Error: 'static, { @@ -153,7 +153,7 @@ where type Future = Box, Error = Error>>; #[inline] - fn from_request(req: &HttpRequest, payload: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { Box::new( T::from_request(req, payload) .into_future() @@ -166,11 +166,11 @@ where } #[doc(hidden)] -impl

FromRequest

for () { +impl FromRequest for () { type Error = Error; type Future = Result<(), Error>; - fn from_request(_: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(_: &HttpRequest, _: &mut Payload) -> Self::Future { Ok(()) } } @@ -179,12 +179,12 @@ macro_rules! tuple_from_req ({$fut_type:ident, $(($n:tt, $T:ident)),+} => { /// FromRequest implementation for tuple #[doc(hidden)] - impl + 'static),+> FromRequest

for ($($T,)+) + impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+) { type Error = Error; - type Future = $fut_type; + type Future = $fut_type<$($T),+>; - fn from_request(req: &HttpRequest, payload: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { $fut_type { items: <($(Option<$T>,)+)>::default(), futs: ($($T::from_request(req, payload).into_future(),)+), @@ -193,12 +193,12 @@ macro_rules! tuple_from_req ({$fut_type:ident, $(($n:tt, $T:ident)),+} => { } #[doc(hidden)] - pub struct $fut_type),+> { + pub struct $fut_type<$($T: FromRequest),+> { items: ($(Option<$T>,)+), futs: ($(<$T::Future as futures::IntoFuture>::Future,)+), } - impl),+> Future for $fut_type + impl<$($T: FromRequest),+> Future for $fut_type<$($T),+> { type Item = ($($T,)+); type Error = Error; diff --git a/src/handler.rs b/src/handler.rs index 42a9d88d..f328cd25 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -242,13 +242,13 @@ where } /// Extract arguments from request -pub struct Extract, S> { +pub struct Extract { config: Rc>>>, service: S, - _t: PhantomData<(P, T)>, + _t: PhantomData, } -impl, S> Extract { +impl Extract { pub fn new(config: Rc>>>, service: S) -> Self { Extract { config, @@ -258,16 +258,16 @@ impl, S> Extract { } } -impl, S> NewService for Extract +impl NewService for Extract where S: Service + Clone, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; - type Error = (Error, ServiceRequest

); + type Error = (Error, ServiceRequest); type InitError = (); - type Service = ExtractService; + type Service = ExtractService; type Future = FutureResult; fn new_service(&self, _: &()) -> Self::Future { @@ -279,27 +279,27 @@ where } } -pub struct ExtractService, S> { +pub struct ExtractService { config: Option>, service: S, - _t: PhantomData<(P, T)>, + _t: PhantomData, } -impl, S> Service for ExtractService +impl Service for ExtractService where S: Service + Clone, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; - type Error = (Error, ServiceRequest

); - type Future = ExtractResponse; + type Error = (Error, ServiceRequest); + type Future = ExtractResponse; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(Async::Ready(())) } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { let (mut req, mut payload) = req.into_parts(); req.set_route_data(self.config.clone()); let fut = T::from_request(&req, &mut payload).into_future(); @@ -313,19 +313,19 @@ where } } -pub struct ExtractResponse, S: Service> { - req: Option<(HttpRequest, Payload

)>, +pub struct ExtractResponse { + req: Option<(HttpRequest, Payload)>, service: S, fut: ::Future, fut_s: Option, } -impl, S> Future for ExtractResponse +impl Future for ExtractResponse where S: Service, { type Item = ServiceResponse; - type Error = (Error, ServiceRequest

); + type Error = (Error, ServiceRequest); fn poll(&mut self) -> Poll { if let Some(ref mut fut) = self.fut_s { diff --git a/src/lib.rs b/src/lib.rs index f0600c6c..6636d96d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -133,7 +133,6 @@ pub mod dev { //! use actix_web::dev::*; //! ``` - pub use crate::app::AppRouter; pub use crate::config::{AppConfig, ServiceConfig}; pub use crate::info::ConnectionInfo; pub use crate::rmap::ResourceMap; @@ -143,6 +142,7 @@ pub mod dev { pub use crate::types::readlines::Readlines; pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody}; + pub use actix_http::encoding::Decoder as Decompress; pub use actix_http::ResponseBuilder as HttpResponseBuilder; pub use actix_http::{ Extensions, Payload, PayloadStream, RequestHead, ResponseHead, diff --git a/src/middleware/compress.rs b/src/middleware/compress.rs index a4b6a460..d5c4082e 100644 --- a/src/middleware/compress.rs +++ b/src/middleware/compress.rs @@ -41,11 +41,11 @@ impl BodyEncoding for Response { /// To disable compression set encoding to `ContentEncoding::Identity` value. /// /// ```rust -/// use actix_web::{web, middleware::encoding, App, HttpResponse}; +/// use actix_web::{web, middleware, App, HttpResponse}; /// /// fn main() { /// let app = App::new() -/// .wrap(encoding::Compress::default()) +/// .wrap(middleware::Compress::default()) /// .service( /// web::resource("/test") /// .route(web::get().to(|| HttpResponse::Ok())) @@ -68,12 +68,12 @@ impl Default for Compress { } } -impl Transform for Compress +impl Transform for Compress where B: MessageBody, - S: Service, Response = ServiceResponse>, + S: Service>, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse>; type Error = S::Error; type InitError = (); @@ -93,21 +93,21 @@ pub struct CompressMiddleware { encoding: ContentEncoding, } -impl Service for CompressMiddleware +impl Service for CompressMiddleware where B: MessageBody, - S: Service, Response = ServiceResponse>, + S: Service>, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse>; type Error = S::Error; - type Future = CompressResponse; + type Future = CompressResponse; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { // negotiate content-encoding let encoding = if let Some(val) = req.headers().get(&ACCEPT_ENCODING) { if let Ok(enc) = val.to_str() { @@ -128,20 +128,20 @@ where } #[doc(hidden)] -pub struct CompressResponse +pub struct CompressResponse where S: Service, B: MessageBody, { fut: S::Future, encoding: ContentEncoding, - _t: PhantomData<(P, B)>, + _t: PhantomData<(B)>, } -impl Future for CompressResponse +impl Future for CompressResponse where B: MessageBody, - S: Service, Response = ServiceResponse>, + S: Service>, { type Item = ServiceResponse>; type Error = S::Error; diff --git a/src/middleware/cors.rs b/src/middleware/cors.rs index 27d24b43..1fa6e669 100644 --- a/src/middleware/cors.rs +++ b/src/middleware/cors.rs @@ -475,9 +475,9 @@ fn cors<'a>( parts.as_mut() } -impl IntoTransform for Cors +impl IntoTransform for Cors where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, S::Error: 'static, B: 'static, @@ -537,14 +537,14 @@ pub struct CorsFactory { inner: Rc, } -impl Transform for CorsFactory +impl Transform for CorsFactory where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, S::Error: 'static, B: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type InitError = (); @@ -678,14 +678,14 @@ impl Inner { } } -impl Service for CorsMiddleware +impl Service for CorsMiddleware where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, S::Error: 'static, B: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type Future = Either< @@ -697,7 +697,7 @@ where self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { if self.inner.preflight && Method::OPTIONS == *req.method() { if let Err(e) = self .inner @@ -815,13 +815,12 @@ mod tests { use actix_service::{FnService, Transform}; use super::*; - use crate::dev::PayloadStream; use crate::test::{self, block_on, TestRequest}; impl Cors { - fn finish(self, srv: S) -> CorsMiddleware + fn finish(self, srv: S) -> CorsMiddleware where - S: Service, Response = ServiceResponse> + S: Service> + 'static, S::Future: 'static, S::Error: 'static, @@ -1057,7 +1056,7 @@ mod tests { .allowed_headers(exposed_headers.clone()) .expose_headers(exposed_headers.clone()) .allowed_header(header::CONTENT_TYPE) - .finish(FnService::new(move |req: ServiceRequest| { + .finish(FnService::new(move |req: ServiceRequest| { req.into_response( HttpResponse::Ok().header(header::VARY, "Accept").finish(), ) diff --git a/src/middleware/decompress.rs b/src/middleware/decompress.rs deleted file mode 100644 index 13735143..00000000 --- a/src/middleware/decompress.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! Chain service for decompressing request payload. -use std::marker::PhantomData; - -use actix_http::encoding::Decoder; -use actix_service::{NewService, Service}; -use bytes::Bytes; -use futures::future::{ok, FutureResult}; -use futures::{Async, Poll, Stream}; - -use crate::dev::Payload; -use crate::error::{Error, PayloadError}; -use crate::service::ServiceRequest; - -/// `Middleware` for decompressing request's payload. -/// `Decompress` middleware must be added with `App::chain()` method. -/// -/// ```rust -/// use actix_web::{web, middleware::encoding, App, HttpResponse}; -/// -/// fn main() { -/// let app = App::new() -/// .chain(encoding::Decompress::new()) -/// .service( -/// web::resource("/test") -/// .route(web::get().to(|| HttpResponse::Ok())) -/// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) -/// ); -/// } -/// ``` -pub struct Decompress

(PhantomData

); - -impl

Decompress

-where - P: Stream, -{ - pub fn new() -> Self { - Decompress(PhantomData) - } -} - -impl

NewService for Decompress

-where - P: Stream, -{ - type Request = ServiceRequest

; - type Response = ServiceRequest>>; - type Error = Error; - type InitError = (); - type Service = Decompress

; - type Future = FutureResult; - - fn new_service(&self, _: &()) -> Self::Future { - ok(Decompress(PhantomData)) - } -} - -impl

Service for Decompress

-where - P: Stream, -{ - type Request = ServiceRequest

; - type Response = ServiceRequest>>; - type Error = Error; - type Future = FutureResult; - - fn poll_ready(&mut self) -> Poll<(), Self::Error> { - Ok(Async::Ready(())) - } - - fn call(&mut self, req: ServiceRequest

) -> Self::Future { - let (req, payload) = req.into_parts(); - let payload = Decoder::from_headers(payload, req.headers()); - ok(ServiceRequest::from_parts(req, Payload::Stream(payload))) - } -} diff --git a/src/middleware/defaultheaders.rs b/src/middleware/defaultheaders.rs index a2bc6f27..c0e62e28 100644 --- a/src/middleware/defaultheaders.rs +++ b/src/middleware/defaultheaders.rs @@ -85,12 +85,12 @@ impl DefaultHeaders { } } -impl Transform for DefaultHeaders +impl Transform for DefaultHeaders where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type InitError = (); @@ -110,12 +110,12 @@ pub struct DefaultHeadersMiddleware { inner: Rc, } -impl Service for DefaultHeadersMiddleware +impl Service for DefaultHeadersMiddleware where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type Future = Box>; @@ -124,7 +124,7 @@ where self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { let inner = self.inner.clone(); Box::new(self.service.call(req).map(move |mut res| { @@ -171,7 +171,7 @@ mod tests { assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); let req = TestRequest::default().to_srv_request(); - let srv = FnService::new(|req: ServiceRequest<_>| { + let srv = FnService::new(|req: ServiceRequest| { req.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish()) }); let mut mw = block_on( @@ -186,7 +186,7 @@ mod tests { #[test] fn test_content_type() { - let srv = FnService::new(|req: ServiceRequest<_>| { + let srv = FnService::new(|req: ServiceRequest| { req.into_response(HttpResponse::Ok().finish()) }); let mut mw = diff --git a/src/middleware/errhandlers.rs b/src/middleware/errhandlers.rs index a69bdaf9..56745630 100644 --- a/src/middleware/errhandlers.rs +++ b/src/middleware/errhandlers.rs @@ -81,18 +81,14 @@ impl ErrorHandlers { } } -impl Transform for ErrorHandlers +impl Transform for ErrorHandlers where - S: Service< - Request = ServiceRequest

, - Response = ServiceResponse, - Error = Error, - >, + S: Service, Error = Error>, S::Future: 'static, S::Error: 'static, B: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); @@ -113,18 +109,14 @@ pub struct ErrorHandlersMiddleware { handlers: Rc>>>, } -impl Service for ErrorHandlersMiddleware +impl Service for ErrorHandlersMiddleware where - S: Service< - Request = ServiceRequest

, - Response = ServiceResponse, - Error = Error, - >, + S: Service, Error = Error>, S::Future: 'static, S::Error: 'static, B: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = Box>; @@ -133,7 +125,7 @@ where self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { let handlers = self.handlers.clone(); Box::new(self.service.call(req).and_then(move |res| { @@ -169,7 +161,7 @@ mod tests { #[test] fn test_handler() { - let srv = FnService::new(|req: ServiceRequest<_>| { + let srv = FnService::new(|req: ServiceRequest| { req.into_response(HttpResponse::InternalServerError().finish()) }); @@ -195,7 +187,7 @@ mod tests { #[test] fn test_handler_async() { - let srv = FnService::new(|req: ServiceRequest<_>| { + let srv = FnService::new(|req: ServiceRequest| { req.into_response(HttpResponse::InternalServerError().finish()) }); diff --git a/src/middleware/identity.rs b/src/middleware/identity.rs index e263099f..8dd2ddb8 100644 --- a/src/middleware/identity.rs +++ b/src/middleware/identity.rs @@ -140,12 +140,12 @@ struct IdentityItem { /// } /// # fn main() {} /// ``` -impl

FromRequest

for Identity { +impl FromRequest for Identity { type Error = Error; type Future = Result; #[inline] - fn from_request(req: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { Ok(Identity(req.clone())) } } @@ -159,7 +159,7 @@ pub trait IdentityPolicy: Sized + 'static { type ResponseFuture: IntoFuture; /// Parse the session from request and load data from a service identity. - fn from_request

(&self, request: &mut ServiceRequest

) -> Self::Future; + fn from_request(&self, request: &mut ServiceRequest) -> Self::Future; /// Write changes to response fn to_response( @@ -198,16 +198,15 @@ impl IdentityService { } } -impl Transform for IdentityService +impl Transform for IdentityService where - S: Service, Response = ServiceResponse> + 'static, + S: Service> + 'static, S::Future: 'static, S::Error: 'static, T: IdentityPolicy, - P: 'static, B: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type InitError = (); @@ -228,16 +227,15 @@ pub struct IdentityServiceMiddleware { service: Rc>, } -impl Service for IdentityServiceMiddleware +impl Service for IdentityServiceMiddleware where - P: 'static, B: 'static, - S: Service, Response = ServiceResponse> + 'static, + S: Service> + 'static, S::Future: 'static, S::Error: 'static, T: IdentityPolicy, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type Future = Box>; @@ -246,7 +244,7 @@ where self.service.borrow_mut().poll_ready() } - fn call(&mut self, mut req: ServiceRequest

) -> Self::Future { + fn call(&mut self, mut req: ServiceRequest) -> Self::Future { let srv = self.service.clone(); let backend = self.backend.clone(); @@ -348,7 +346,7 @@ impl CookieIdentityInner { Ok(()) } - fn load(&self, req: &ServiceRequest) -> Option { + fn load(&self, req: &ServiceRequest) -> Option { if let Ok(cookies) = req.cookies() { for cookie in cookies.iter() { if cookie.name() == self.name { @@ -445,7 +443,7 @@ impl IdentityPolicy for CookieIdentityPolicy { type Future = Result, Error>; type ResponseFuture = Result<(), Error>; - fn from_request

(&self, req: &mut ServiceRequest

) -> Self::Future { + fn from_request(&self, req: &mut ServiceRequest) -> Self::Future { Ok(self.0.load(req)) } diff --git a/src/middleware/logger.rs b/src/middleware/logger.rs index 66ca150b..d5fca526 100644 --- a/src/middleware/logger.rs +++ b/src/middleware/logger.rs @@ -114,12 +114,12 @@ impl Default for Logger { } } -impl Transform for Logger +impl Transform for Logger where - S: Service, Response = ServiceResponse>, + S: Service>, B: MessageBody, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse>; type Error = S::Error; type InitError = (); @@ -140,21 +140,21 @@ pub struct LoggerMiddleware { service: S, } -impl Service for LoggerMiddleware +impl Service for LoggerMiddleware where - S: Service, Response = ServiceResponse>, + S: Service>, B: MessageBody, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse>; type Error = S::Error; - type Future = LoggerResponse; + type Future = LoggerResponse; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { if self.inner.exclude.contains(req.path()) { LoggerResponse { fut: self.service.call(req), @@ -180,7 +180,7 @@ where } #[doc(hidden)] -pub struct LoggerResponse +pub struct LoggerResponse where B: MessageBody, S: Service, @@ -188,13 +188,13 @@ where fut: S::Future, time: time::Tm, format: Option, - _t: PhantomData<(P, B)>, + _t: PhantomData<(B,)>, } -impl Future for LoggerResponse +impl Future for LoggerResponse where B: MessageBody, - S: Service, Response = ServiceResponse>, + S: Service>, { type Item = ServiceResponse>; type Error = S::Error; @@ -402,7 +402,7 @@ impl FormatText { } } - fn render_request

(&mut self, now: time::Tm, req: &ServiceRequest

) { + fn render_request(&mut self, now: time::Tm, req: &ServiceRequest) { match *self { FormatText::RequestLine => { *self = if req.query_string().is_empty() { @@ -464,7 +464,7 @@ mod tests { #[test] fn test_logger() { - let srv = FnService::new(|req: ServiceRequest<_>| { + let srv = FnService::new(|req: ServiceRequest| { req.into_response( HttpResponse::build(StatusCode::OK) .header("X-Test", "ttt") diff --git a/src/middleware/mod.rs b/src/middleware/mod.rs index 6b6253fb..59d467c0 100644 --- a/src/middleware/mod.rs +++ b/src/middleware/mod.rs @@ -1,14 +1,6 @@ //! Middlewares -#[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] mod compress; -#[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] -mod decompress; -#[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] -pub mod encoding { - //! Middlewares for compressing/decompressing payloads. - pub use super::compress::{BodyEncoding, Compress}; - pub use super::decompress::Decompress; -} +pub use self::compress::{BodyEncoding, Compress}; pub mod cors; mod defaultheaders; diff --git a/src/request.rs b/src/request.rs index 53d848f0..93ac954f 100644 --- a/src/request.rs +++ b/src/request.rs @@ -265,12 +265,12 @@ impl Drop for HttpRequest { /// ); /// } /// ``` -impl

FromRequest

for HttpRequest { +impl FromRequest for HttpRequest { type Error = Error; type Future = Result; #[inline] - fn from_request(req: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { Ok(req.clone()) } } diff --git a/src/resource.rs b/src/resource.rs index 313a3bc0..f0dea981 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -17,9 +17,8 @@ use crate::responder::Responder; use crate::route::{CreateRouteService, Route, RouteService}; use crate::service::{ServiceRequest, ServiceResponse}; -type HttpService

= BoxedService, ServiceResponse, Error>; -type HttpNewService

= - BoxedNewService<(), ServiceRequest

, ServiceResponse, Error, ()>; +type HttpService = BoxedService; +type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; /// *Resource* is an entry in resources table which corresponds to requested URL. /// @@ -43,18 +42,18 @@ type HttpNewService

= /// /// If no matching route could be found, *405* response code get returned. /// Default behavior could be overriden with `default_resource()` method. -pub struct Resource> { +pub struct Resource { endpoint: T, rdef: String, name: Option, - routes: Vec>, + routes: Vec, guards: Vec>, - default: Rc>>>>, - factory_ref: Rc>>>, + default: Rc>>>, + factory_ref: Rc>>, } -impl

Resource

{ - pub fn new(path: &str) -> Resource

{ +impl Resource { + pub fn new(path: &str) -> Resource { let fref = Rc::new(RefCell::new(None)); Resource { @@ -69,11 +68,10 @@ impl

Resource

{ } } -impl Resource +impl Resource where - P: 'static, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -154,7 +152,7 @@ where /// # fn post_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 } @@ -182,7 +180,7 @@ where pub fn to(mut self, handler: F) -> Self where F: Factory + 'static, - I: FromRequest

+ 'static, + I: FromRequest + 'static, R: Responder + 'static, { self.routes.push(Route::new().to(handler)); @@ -216,7 +214,7 @@ where pub fn to_async(mut self, handler: F) -> Self where F: AsyncFactory, - I: FromRequest

+ 'static, + I: FromRequest + 'static, R: IntoFuture + 'static, R::Item: Into, R::Error: Into, @@ -236,9 +234,8 @@ where self, mw: F, ) -> Resource< - P, impl NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -247,7 +244,7 @@ where where M: Transform< T::Service, - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -302,16 +299,15 @@ where self, mw: F, ) -> Resource< - P, impl NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), >, > where - F: FnMut(ServiceRequest

, &mut T::Service) -> R + Clone, + F: FnMut(ServiceRequest, &mut T::Service) -> R + Clone, R: IntoFuture, { self.wrap(mw) @@ -322,10 +318,10 @@ where /// default handler from `App` or `Scope`. pub fn default_resource(mut self, f: F) -> Self where - F: FnOnce(Resource

) -> R, + F: FnOnce(Resource) -> R, R: IntoNewService, U: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, > + 'static, @@ -339,17 +335,16 @@ where } } -impl HttpServiceFactory

for Resource +impl HttpServiceFactory for Resource where - P: 'static, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), > + 'static, { - fn register(mut self, config: &mut ServiceConfig

) { + fn register(mut self, config: &mut ServiceConfig) { let guards = if self.guards.is_empty() { None } else { @@ -367,10 +362,10 @@ where } } -impl IntoNewService for Resource +impl IntoNewService for Resource where T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -386,18 +381,18 @@ where } } -pub struct ResourceFactory

{ - routes: Vec>, - default: Rc>>>>, +pub struct ResourceFactory { + routes: Vec, + default: Rc>>>, } -impl NewService for ResourceFactory

{ - type Request = ServiceRequest

; +impl NewService for ResourceFactory { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = ResourceService

; - type Future = CreateResourceService

; + type Service = ResourceService; + type Future = CreateResourceService; fn new_service(&self, _: &()) -> Self::Future { let default_fut = if let Some(ref default) = *self.default.borrow() { @@ -418,19 +413,19 @@ impl NewService for ResourceFactory

{ } } -enum CreateRouteServiceItem

{ - Future(CreateRouteService

), - Service(RouteService

), +enum CreateRouteServiceItem { + Future(CreateRouteService), + Service(RouteService), } -pub struct CreateResourceService

{ - fut: Vec>, - default: Option>, - default_fut: Option, Error = ()>>>, +pub struct CreateResourceService { + fut: Vec, + default: Option, + default_fut: Option>>, } -impl

Future for CreateResourceService

{ - type Item = ResourceService

; +impl Future for CreateResourceService { + type Item = ResourceService; type Error = (); fn poll(&mut self) -> Poll { @@ -477,13 +472,13 @@ impl

Future for CreateResourceService

{ } } -pub struct ResourceService

{ - routes: Vec>, - default: Option>, +pub struct ResourceService { + routes: Vec, + default: Option, } -impl

Service for ResourceService

{ - type Request = ServiceRequest

; +impl Service for ResourceService { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = Either< @@ -495,7 +490,7 @@ impl

Service for ResourceService

{ Ok(Async::Ready(())) } - 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() { if route.check(&mut req) { return route.call(req); @@ -514,23 +509,23 @@ impl

Service for ResourceService

{ } #[doc(hidden)] -pub struct ResourceEndpoint

{ - factory: Rc>>>, +pub struct ResourceEndpoint { + factory: Rc>>, } -impl

ResourceEndpoint

{ - fn new(factory: Rc>>>) -> Self { +impl ResourceEndpoint { + fn new(factory: Rc>>) -> Self { ResourceEndpoint { factory } } } -impl NewService for ResourceEndpoint

{ - type Request = ServiceRequest

; +impl NewService for ResourceEndpoint { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = ResourceService

; - type Future = CreateResourceService

; + type Service = ResourceService; + type Future = CreateResourceService; fn new_service(&self, _: &()) -> Self::Future { self.factory.borrow_mut().as_mut().unwrap().new_service(&()) @@ -550,13 +545,13 @@ mod tests { use crate::test::{call_success, init_service, TestRequest}; use crate::{web, App, Error, HttpResponse}; - fn md( - req: ServiceRequest

, + fn md( + req: ServiceRequest, srv: &mut S, ) -> impl IntoFuture, Error = Error> where S: Service< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, >, diff --git a/src/route.rs b/src/route.rs index 8bff863f..eb911b30 100644 --- a/src/route.rs +++ b/src/route.rs @@ -1,5 +1,4 @@ use std::cell::RefCell; -use std::marker::PhantomData; use std::rc::Rc; use actix_http::{http::Method, Error, Extensions, Response}; @@ -42,16 +41,16 @@ type BoxedRouteNewService = Box< /// /// Route uses builder-like pattern for configuration. /// If handler is not explicitly set, default *404 Not Found* handler is used. -pub struct Route

{ - service: BoxedRouteNewService, ServiceResponse>, +pub struct Route { + service: BoxedRouteNewService, guards: Rc>>, data: Option, data_ref: Rc>>>, } -impl Route

{ +impl Route { /// Create new route which matches any request. - pub fn new() -> Route

{ + pub fn new() -> Route { let data_ref = Rc::new(RefCell::new(None)); Route { service: Box::new(RouteNewService::new(Extract::new( @@ -74,13 +73,13 @@ impl Route

{ } } -impl

NewService for Route

{ - type Request = ServiceRequest

; +impl NewService for Route { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = RouteService

; - type Future = CreateRouteService

; + type Service = RouteService; + type Future = CreateRouteService; fn new_service(&self, _: &()) -> Self::Future { CreateRouteService { @@ -90,17 +89,16 @@ impl

NewService for Route

{ } } -type RouteFuture

= Box< - Future, ServiceResponse>, Error = ()>, ->; +type RouteFuture = + Box, Error = ()>>; -pub struct CreateRouteService

{ - fut: RouteFuture

, +pub struct CreateRouteService { + fut: RouteFuture, guards: Rc>>, } -impl

Future for CreateRouteService

{ - type Item = RouteService

; +impl Future for CreateRouteService { + type Item = RouteService; type Error = (); fn poll(&mut self) -> Poll { @@ -114,13 +112,13 @@ impl

Future for CreateRouteService

{ } } -pub struct RouteService

{ - service: BoxedRouteService, ServiceResponse>, +pub struct RouteService { + service: BoxedRouteService, guards: Rc>>, } -impl

RouteService

{ - pub fn check(&self, req: &mut ServiceRequest

) -> bool { +impl RouteService { + pub fn check(&self, req: &mut ServiceRequest) -> bool { for f in self.guards.iter() { if !f.check(req.head()) { return false; @@ -130,8 +128,8 @@ impl

RouteService

{ } } -impl

Service for RouteService

{ - type Request = ServiceRequest

; +impl Service for RouteService { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = Either< @@ -143,12 +141,12 @@ impl

Service for RouteService

{ self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { self.service.call(req) } } -impl Route

{ +impl Route { /// Add method guard to the route. /// /// ```rust @@ -235,10 +233,10 @@ impl Route

{ /// ); /// } /// ``` - pub fn to(mut self, handler: F) -> Route

+ pub fn to(mut self, handler: F) -> Route where F: Factory + 'static, - T: FromRequest

+ 'static, + T: FromRequest + 'static, R: Responder + 'static, { self.service = Box::new(RouteNewService::new(Extract::new( @@ -278,7 +276,7 @@ impl Route

{ pub fn to_async(mut self, handler: F) -> Self where F: AsyncFactory, - T: FromRequest

+ 'static, + T: FromRequest + 'static, R: IntoFuture + 'static, R::Item: Into, R::Error: Into, @@ -321,49 +319,45 @@ impl Route

{ } } -struct RouteNewService +struct RouteNewService where - T: NewService, Error = (Error, ServiceRequest

)>, + T: NewService, { service: T, - _t: PhantomData

, } -impl RouteNewService +impl RouteNewService where T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, - Error = (Error, ServiceRequest

), + Error = (Error, ServiceRequest), >, T::Future: 'static, T::Service: 'static, ::Future: 'static, { pub fn new(service: T) -> Self { - RouteNewService { - service, - _t: PhantomData, - } + RouteNewService { service } } } -impl NewService for RouteNewService +impl NewService for RouteNewService where T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, - Error = (Error, ServiceRequest

), + Error = (Error, ServiceRequest), >, T::Future: 'static, T::Service: 'static, ::Future: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = BoxedRouteService, Self::Response>; + type Service = BoxedRouteService; type Future = Box>; fn new_service(&self, _: &()) -> Self::Future { @@ -373,31 +367,27 @@ where .map_err(|_| ()) .and_then(|service| { let service: BoxedRouteService<_, _> = - Box::new(RouteServiceWrapper { - service, - _t: PhantomData, - }); + Box::new(RouteServiceWrapper { service }); Ok(service) }), ) } } -struct RouteServiceWrapper { +struct RouteServiceWrapper { service: T, - _t: PhantomData

, } -impl Service for RouteServiceWrapper +impl Service for RouteServiceWrapper where T::Future: 'static, T: Service< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, - Error = (Error, ServiceRequest

), + Error = (Error, ServiceRequest), >, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = Either< @@ -409,7 +399,7 @@ where self.service.poll_ready().map_err(|(e, _)| e) } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { let mut fut = self.service.call(req); match fut.poll() { Ok(Async::Ready(res)) => Either::A(ok(res)), diff --git a/src/scope.rs b/src/scope.rs index 2cb01961..62badc86 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -21,9 +21,8 @@ use crate::service::{ }; type Guards = Vec>; -type HttpService

= BoxedService, ServiceResponse, Error>; -type HttpNewService

= - BoxedNewService<(), ServiceRequest

, ServiceResponse, Error, ()>; +type HttpService = BoxedService; +type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type BoxedResponse = Either< FutureResult, Box>, @@ -58,18 +57,18 @@ type BoxedResponse = Either< /// * /{project_id}/path2 - `GET` requests /// * /{project_id}/path3 - `HEAD` requests /// -pub struct Scope> { +pub struct Scope { endpoint: T, rdef: String, - services: Vec>>, + services: Vec>, guards: Vec>, - default: Rc>>>>, - factory_ref: Rc>>>, + default: Rc>>>, + factory_ref: Rc>>, } -impl Scope

{ +impl Scope { /// Create a new scope - pub fn new(path: &str) -> Scope

{ + pub fn new(path: &str) -> Scope { let fref = Rc::new(RefCell::new(None)); Scope { endpoint: ScopeEndpoint::new(fref.clone()), @@ -82,11 +81,10 @@ impl Scope

{ } } -impl Scope +impl Scope where - P: 'static, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -146,7 +144,7 @@ where /// ``` pub fn service(mut self, factory: F) -> Self where - F: HttpServiceFactory

+ 'static, + F: HttpServiceFactory + 'static, { self.services .push(Box::new(ServiceFactoryWrapper::new(factory))); @@ -174,7 +172,7 @@ where /// ); /// } /// ``` - pub fn route(self, path: &str, mut route: Route

) -> Self { + pub fn route(self, path: &str, mut route: Route) -> Self { self.service( Resource::new(path) .add_guards(route.take_guards()) @@ -187,9 +185,9 @@ where /// If default resource is not registered, app's default resource is being used. pub fn default_resource(mut self, f: F) -> Self where - F: FnOnce(Resource

) -> Resource, + F: FnOnce(Resource) -> Resource, U: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -216,9 +214,8 @@ where self, mw: F, ) -> Scope< - P, impl NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -227,7 +224,7 @@ where where M: Transform< T::Service, - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), @@ -279,33 +276,31 @@ where self, mw: F, ) -> Scope< - P, impl NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), >, > where - F: FnMut(ServiceRequest

, &mut T::Service) -> R + Clone, + F: FnMut(ServiceRequest, &mut T::Service) -> R + Clone, R: IntoFuture, { self.wrap(mw) } } -impl HttpServiceFactory

for Scope +impl HttpServiceFactory for Scope where - P: 'static, T: NewService< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, InitError = (), > + 'static, { - fn register(self, config: &mut ServiceConfig

) { + fn register(self, config: &mut ServiceConfig) { // update default resource if needed if self.default.borrow().is_none() { *self.default.borrow_mut() = Some(config.default_service()); @@ -350,18 +345,18 @@ where } } -pub struct ScopeFactory

{ - services: Rc, RefCell>)>>, - default: Rc>>>>, +pub struct ScopeFactory { + services: Rc>)>>, + default: Rc>>>, } -impl NewService for ScopeFactory

{ - type Request = ServiceRequest

; +impl NewService for ScopeFactory { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = ScopeService

; - type Future = ScopeFactoryResponse

; + type Service = ScopeService; + type Future = ScopeFactoryResponse; fn new_service(&self, _: &()) -> Self::Future { let default_fut = if let Some(ref default) = *self.default.borrow() { @@ -390,21 +385,21 @@ impl NewService for ScopeFactory

{ /// Create scope service #[doc(hidden)] -pub struct ScopeFactoryResponse

{ - fut: Vec>, - default: Option>, - default_fut: Option, Error = ()>>>, +pub struct ScopeFactoryResponse { + fut: Vec, + default: Option, + default_fut: Option>>, } -type HttpServiceFut

= Box, Error = ()>>; +type HttpServiceFut = Box>; -enum CreateScopeServiceItem

{ - Future(Option, Option, HttpServiceFut

), - Service(ResourceDef, Option, HttpService

), +enum CreateScopeServiceItem { + Future(Option, Option, HttpServiceFut), + Service(ResourceDef, Option, HttpService), } -impl

Future for ScopeFactoryResponse

{ - type Item = ScopeService

; +impl Future for ScopeFactoryResponse { + type Item = ScopeService; type Error = (); fn poll(&mut self) -> Poll { @@ -465,14 +460,14 @@ impl

Future for ScopeFactoryResponse

{ } } -pub struct ScopeService

{ - router: Router, Vec>>, - default: Option>, - _ready: Option<(ServiceRequest

, ResourceInfo)>, +pub struct ScopeService { + router: Router>>, + default: Option, + _ready: Option<(ServiceRequest, ResourceInfo)>, } -impl

Service for ScopeService

{ - type Request = ServiceRequest

; +impl Service for ScopeService { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type Future = Either>; @@ -481,7 +476,7 @@ impl

Service for ScopeService

{ Ok(Async::Ready(())) } - fn call(&mut self, mut req: ServiceRequest

) -> Self::Future { + fn call(&mut self, mut req: ServiceRequest) -> Self::Future { let res = self.router.recognize_mut_checked(&mut req, |req, guards| { if let Some(ref guards) = guards { for f in guards { @@ -505,23 +500,23 @@ impl

Service for ScopeService

{ } #[doc(hidden)] -pub struct ScopeEndpoint

{ - factory: Rc>>>, +pub struct ScopeEndpoint { + factory: Rc>>, } -impl

ScopeEndpoint

{ - fn new(factory: Rc>>>) -> Self { +impl ScopeEndpoint { + fn new(factory: Rc>>) -> Self { ScopeEndpoint { factory } } } -impl NewService for ScopeEndpoint

{ - type Request = ServiceRequest

; +impl NewService for ScopeEndpoint { + type Request = ServiceRequest; type Response = ServiceResponse; type Error = Error; type InitError = (); - type Service = ScopeService

; - type Future = ScopeFactoryResponse

; + type Service = ScopeService; + type Future = ScopeFactoryResponse; fn new_service(&self, _: &()) -> Self::Future { self.factory.borrow_mut().as_mut().unwrap().new_service(&()) @@ -886,13 +881,13 @@ mod tests { assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); } - fn md( - req: ServiceRequest

, + fn md( + req: ServiceRequest, srv: &mut S, ) -> impl IntoFuture, Error = Error> where S: Service< - Request = ServiceRequest

, + Request = ServiceRequest, Response = ServiceResponse, Error = Error, >, diff --git a/src/service.rs b/src/service.rs index 01875854..2817cc0b 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1,6 +1,5 @@ use std::cell::{Ref, RefMut}; use std::fmt; -use std::marker::PhantomData; use actix_http::body::{Body, MessageBody, ResponseBody}; use actix_http::http::{HeaderMap, Method, StatusCode, Uri, Version}; @@ -15,52 +14,50 @@ use crate::config::{AppConfig, ServiceConfig}; use crate::data::Data; use crate::request::HttpRequest; -pub trait HttpServiceFactory

{ - fn register(self, config: &mut ServiceConfig

); +pub trait HttpServiceFactory { + fn register(self, config: &mut ServiceConfig); } -pub(crate) trait ServiceFactory

{ - fn register(&mut self, config: &mut ServiceConfig

); +pub(crate) trait ServiceFactory { + fn register(&mut self, config: &mut ServiceConfig); } -pub(crate) struct ServiceFactoryWrapper { +pub(crate) struct ServiceFactoryWrapper { factory: Option, - _t: PhantomData

, } -impl ServiceFactoryWrapper { +impl ServiceFactoryWrapper { pub fn new(factory: T) -> Self { Self { factory: Some(factory), - _t: PhantomData, } } } -impl ServiceFactory

for ServiceFactoryWrapper +impl ServiceFactory for ServiceFactoryWrapper where - T: HttpServiceFactory

, + T: HttpServiceFactory, { - fn register(&mut self, config: &mut ServiceConfig

) { + fn register(&mut self, config: &mut ServiceConfig) { if let Some(item) = self.factory.take() { item.register(config) } } } -pub struct ServiceRequest

{ +pub struct ServiceRequest { req: HttpRequest, - payload: Payload

, + payload: Payload, } -impl

ServiceRequest

{ +impl ServiceRequest { /// Construct service request from parts - pub fn from_parts(req: HttpRequest, payload: Payload

) -> Self { + pub fn from_parts(req: HttpRequest, payload: Payload) -> Self { ServiceRequest { req, payload } } /// Deconstruct request into parts - pub fn into_parts(self) -> (HttpRequest, Payload

) { + pub fn into_parts(self) -> (HttpRequest, Payload) { (self.req, self.payload) } @@ -170,14 +167,14 @@ impl

ServiceRequest

{ } } -impl

Resource for ServiceRequest

{ +impl Resource for ServiceRequest { fn resource_path(&mut self) -> &mut Path { self.match_info_mut() } } -impl

HttpMessage for ServiceRequest

{ - type Stream = P; +impl HttpMessage for ServiceRequest { + type Stream = PayloadStream; #[inline] /// Returns Request's headers. @@ -203,7 +200,7 @@ impl

HttpMessage for ServiceRequest

{ } } -impl

fmt::Debug for ServiceRequest

{ +impl fmt::Debug for ServiceRequest { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!( f, diff --git a/src/test.rs b/src/test.rs index f52aefc4..7cdf4485 100644 --- a/src/test.rs +++ b/src/test.rs @@ -6,7 +6,7 @@ use actix_http::cookie::Cookie; use actix_http::http::header::{Header, HeaderName, IntoHeaderValue}; use actix_http::http::{HttpTryFrom, Method, StatusCode, Version}; use actix_http::test::TestRequest as HttpTestRequest; -use actix_http::{Extensions, PayloadStream, Request}; +use actix_http::{Extensions, Request}; use actix_router::{Path, ResourceDef, Url}; use actix_rt::Runtime; use actix_server_config::ServerConfig; @@ -60,23 +60,18 @@ where } /// Create service that always responds with `HttpResponse::Ok()` -pub fn ok_service() -> impl Service< - Request = ServiceRequest, - Response = ServiceResponse, - Error = Error, -> { +pub fn ok_service( +) -> impl Service, Error = Error> +{ default_service(StatusCode::OK) } /// Create service that responds with response with specified status code pub fn default_service( status_code: StatusCode, -) -> impl Service< - Request = ServiceRequest, - Response = ServiceResponse, - Error = Error, -> { - FnService::new(move |req: ServiceRequest| { +) -> impl Service, Error = Error> +{ + FnService::new(move |req: ServiceRequest| { req.into_response(HttpResponse::build(status_code).finish()) }) } @@ -298,12 +293,12 @@ impl TestRequest { } /// Complete request creation and generate `Request` instance - pub fn to_request(mut self) -> Request { + pub fn to_request(mut self) -> Request { self.req.finish() } /// Complete request creation and generate `ServiceRequest` instance - pub fn to_srv_request(mut self) -> ServiceRequest { + pub fn to_srv_request(mut self) -> ServiceRequest { let (head, payload) = self.req.finish().into_parts(); let req = HttpRequest::new( diff --git a/src/types/form.rs b/src/types/form.rs index 2c876e26..c2e8c63b 100644 --- a/src/types/form.rs +++ b/src/types/form.rs @@ -3,15 +3,15 @@ use std::rc::Rc; use std::{fmt, ops}; -use actix_http::error::{Error, PayloadError}; -use actix_http::{HttpMessage, Payload}; -use bytes::{Bytes, BytesMut}; +use actix_http::{Error, HttpMessage, Payload}; +use bytes::BytesMut; use encoding::all::UTF_8; use encoding::types::{DecoderTrap, Encoding}; use encoding::EncodingRef; use futures::{Future, Poll, Stream}; use serde::de::DeserializeOwned; +use crate::dev::Decompress; use crate::error::UrlencodedError; use crate::extract::FromRequest; use crate::http::header::CONTENT_LENGTH; @@ -69,16 +69,15 @@ impl ops::DerefMut for Form { } } -impl FromRequest

for Form +impl FromRequest for Form where T: DeserializeOwned + 'static, - P: Stream + 'static, { type Error = Error; type Future = Box>; #[inline] - 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 (limit, err) = req .route_data::() @@ -182,8 +181,8 @@ impl Default for FormConfig { /// * content type is not `application/x-www-form-urlencoded` /// * content-length is greater than 32k /// -pub struct UrlEncoded { - stream: Payload

, +pub struct UrlEncoded { + stream: Option>, limit: usize, length: Option, encoding: EncodingRef, @@ -191,12 +190,9 @@ pub struct UrlEncoded { fut: Option>>, } -impl UrlEncoded -where - P: Stream, -{ +impl UrlEncoded { /// Create a new future to URL encode a request - pub fn new(req: &HttpRequest, payload: &mut Payload

) -> UrlEncoded { + pub fn new(req: &HttpRequest, payload: &mut Payload) -> UrlEncoded { // check content type if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" { return Self::err(UrlencodedError::ContentType); @@ -219,9 +215,10 @@ where } }; + let payload = Decompress::from_headers(payload.take(), req.headers()); UrlEncoded { encoding, - stream: payload.take(), + stream: Some(payload), limit: 32_768, length: len, fut: None, @@ -231,7 +228,7 @@ where fn err(e: UrlencodedError) -> Self { UrlEncoded { - stream: Payload::None, + stream: None, limit: 32_768, fut: None, err: Some(e), @@ -247,9 +244,8 @@ where } } -impl Future for UrlEncoded +impl Future for UrlEncoded where - P: Stream + 'static, U: DeserializeOwned + 'static, { type Item = U; @@ -274,7 +270,10 @@ where // future let encoding = self.encoding; - let fut = std::mem::replace(&mut self.stream, Payload::None) + let fut = self + .stream + .take() + .unwrap() .from_err() .fold(BytesMut::with_capacity(8192), move |mut body, chunk| { if (body.len() + chunk.len()) > limit { @@ -355,20 +354,20 @@ mod tests { TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded") .header(CONTENT_LENGTH, "xxxx") .to_http_parts(); - let info = block_on(UrlEncoded::<_, Info>::new(&req, &mut pl)); + let info = block_on(UrlEncoded::::new(&req, &mut pl)); assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength)); let (req, mut pl) = TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded") .header(CONTENT_LENGTH, "1000000") .to_http_parts(); - let info = block_on(UrlEncoded::<_, Info>::new(&req, &mut pl)); + let info = block_on(UrlEncoded::::new(&req, &mut pl)); assert!(eq(info.err().unwrap(), UrlencodedError::Overflow)); let (req, mut pl) = TestRequest::with_header(CONTENT_TYPE, "text/plain") .header(CONTENT_LENGTH, "10") .to_http_parts(); - let info = block_on(UrlEncoded::<_, Info>::new(&req, &mut pl)); + let info = block_on(UrlEncoded::::new(&req, &mut pl)); assert!(eq(info.err().unwrap(), UrlencodedError::ContentType)); } @@ -380,7 +379,7 @@ mod tests { .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); - let info = block_on(UrlEncoded::<_, Info>::new(&req, &mut pl)).unwrap(); + let info = block_on(UrlEncoded::::new(&req, &mut pl)).unwrap(); assert_eq!( info, Info { @@ -396,7 +395,7 @@ mod tests { .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); - let info = block_on(UrlEncoded::<_, Info>::new(&req, &mut pl)).unwrap(); + let info = block_on(UrlEncoded::::new(&req, &mut pl)).unwrap(); assert_eq!( info, Info { diff --git a/src/types/json.rs b/src/types/json.rs index 5044cf70..d5913622 100644 --- a/src/types/json.rs +++ b/src/types/json.rs @@ -3,7 +3,7 @@ use std::rc::Rc; use std::{fmt, ops}; -use bytes::{Bytes, BytesMut}; +use bytes::BytesMut; use futures::{Future, Poll, Stream}; use serde::de::DeserializeOwned; use serde::Serialize; @@ -12,7 +12,8 @@ use serde_json; use actix_http::http::{header::CONTENT_LENGTH, StatusCode}; use actix_http::{HttpMessage, Payload, Response}; -use crate::error::{Error, JsonPayloadError, PayloadError}; +use crate::dev::Decompress; +use crate::error::{Error, JsonPayloadError}; use crate::extract::FromRequest; use crate::request::HttpRequest; use crate::responder::Responder; @@ -163,16 +164,15 @@ impl Responder for Json { /// ); /// } /// ``` -impl FromRequest

for Json +impl FromRequest for Json where T: DeserializeOwned + 'static, - P: Stream + 'static, { type Error = Error; type Future = Box>; #[inline] - 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 (limit, err) = req .route_data::() @@ -270,21 +270,20 @@ impl Default for JsonConfig { /// /// * content type is not `application/json` /// * content length is greater than 256k -pub struct JsonBody { +pub struct JsonBody { limit: usize, length: Option, - stream: Payload

, + stream: Option>, err: Option, fut: Option>>, } -impl JsonBody +impl JsonBody where - P: Stream + 'static, U: DeserializeOwned + 'static, { /// Create `JsonBody` for request. - pub fn new(req: &HttpRequest, payload: &mut Payload

) -> Self { + pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self { // check content-type let json = if let Ok(Some(mime)) = req.mime_type() { mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON) @@ -295,7 +294,7 @@ where return JsonBody { limit: 262_144, length: None, - stream: Payload::None, + stream: None, fut: None, err: Some(JsonPayloadError::ContentType), }; @@ -309,11 +308,12 @@ where } } } + let payload = Decompress::from_headers(payload.take(), req.headers()); JsonBody { limit: 262_144, length: len, - stream: payload.take(), + stream: Some(payload), fut: None, err: None, } @@ -326,9 +326,8 @@ where } } -impl Future for JsonBody +impl Future for JsonBody where - P: Stream + 'static, U: DeserializeOwned + 'static, { type Item = U; @@ -350,7 +349,10 @@ where } } - let fut = std::mem::replace(&mut self.stream, Payload::None) + let fut = self + .stream + .take() + .unwrap() .from_err() .fold(BytesMut::with_capacity(8192), move |mut body, chunk| { if (body.len() + chunk.len()) > limit { @@ -508,7 +510,7 @@ mod tests { #[test] fn test_json_body() { let (req, mut pl) = TestRequest::default().to_http_parts(); - let json = block_on(JsonBody::<_, MyObject>::new(&req, &mut pl)); + let json = block_on(JsonBody::::new(&req, &mut pl)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); let (req, mut pl) = TestRequest::default() @@ -517,7 +519,7 @@ mod tests { header::HeaderValue::from_static("application/text"), ) .to_http_parts(); - let json = block_on(JsonBody::<_, MyObject>::new(&req, &mut pl)); + let json = block_on(JsonBody::::new(&req, &mut pl)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); let (req, mut pl) = TestRequest::default() @@ -531,7 +533,7 @@ mod tests { ) .to_http_parts(); - let json = block_on(JsonBody::<_, MyObject>::new(&req, &mut pl).limit(100)); + let json = block_on(JsonBody::::new(&req, &mut pl).limit(100)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::Overflow)); let (req, mut pl) = TestRequest::default() @@ -546,7 +548,7 @@ mod tests { .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .to_http_parts(); - let json = block_on(JsonBody::<_, MyObject>::new(&req, &mut pl)); + let json = block_on(JsonBody::::new(&req, &mut pl)); assert_eq!( json.ok().unwrap(), MyObject { diff --git a/src/types/path.rs b/src/types/path.rs index d8334679..47ec1f56 100644 --- a/src/types/path.rs +++ b/src/types/path.rs @@ -152,7 +152,7 @@ impl fmt::Display for Path { /// ); /// } /// ``` -impl FromRequest

for Path +impl FromRequest for Path where T: de::DeserializeOwned, { @@ -160,7 +160,7 @@ where type Future = Result; #[inline] - fn from_request(req: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { de::Deserialize::deserialize(PathDeserializer::new(req.match_info())) .map(|inner| Path { inner }) .map_err(ErrorNotFound) diff --git a/src/types/payload.rs b/src/types/payload.rs index 4c7dbdcc..3dac828c 100644 --- a/src/types/payload.rs +++ b/src/types/payload.rs @@ -44,7 +44,7 @@ use crate::request::HttpRequest; /// ); /// } /// ``` -pub struct Payload(crate::dev::Payload>>); +pub struct Payload(crate::dev::Payload); impl Stream for Payload { type Item = Bytes; @@ -85,26 +85,13 @@ impl Stream for Payload { /// ); /// } /// ``` -impl

FromRequest

for Payload -where - P: Stream + 'static, -{ +impl FromRequest for Payload { type Error = Error; type Future = Result; #[inline] - fn from_request(_: &HttpRequest, payload: &mut dev::Payload

) -> Self::Future { - let pl = match payload.take() { - crate::dev::Payload::Stream(s) => { - let pl: Box> = - Box::new(s); - crate::dev::Payload::Stream(pl) - } - crate::dev::Payload::None => crate::dev::Payload::None, - crate::dev::Payload::H1(pl) => crate::dev::Payload::H1(pl), - crate::dev::Payload::H2(pl) => crate::dev::Payload::H2(pl), - }; - Ok(Payload(pl)) + fn from_request(_: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { + Ok(Payload(payload.take())) } } @@ -133,16 +120,13 @@ where /// ); /// } /// ``` -impl

FromRequest

for Bytes -where - P: Stream + 'static, -{ +impl FromRequest for Bytes { type Error = Error; type Future = Either>, FutureResult>; #[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 cfg = if let Some(cfg) = req.route_data::() { cfg @@ -188,16 +172,13 @@ where /// ); /// } /// ``` -impl

FromRequest

for String -where - P: Stream + 'static, -{ +impl FromRequest for String { type Error = Error; type Future = Either>, FutureResult>; #[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 cfg = if let Some(cfg) = req.route_data::() { cfg @@ -300,20 +281,17 @@ impl Default for PayloadConfig { /// By default only 256Kb payload reads to a memory, then /// `PayloadError::Overflow` get returned. Use `MessageBody::limit()` /// method to change upper limit. -pub struct HttpMessageBody

{ +pub struct HttpMessageBody { limit: usize, length: Option, - stream: dev::Payload

, + stream: Option>, err: Option, fut: Option>>, } -impl

HttpMessageBody

-where - P: Stream, -{ +impl HttpMessageBody { /// Create `MessageBody` for request. - pub fn new(req: &HttpRequest, payload: &mut dev::Payload

) -> HttpMessageBody

{ + pub fn new(req: &HttpRequest, payload: &mut dev::Payload) -> HttpMessageBody { let mut len = None; if let Some(l) = req.headers().get(&header::CONTENT_LENGTH) { if let Ok(s) = l.to_str() { @@ -328,7 +306,7 @@ where } HttpMessageBody { - stream: payload.take(), + stream: Some(dev::Decompress::from_headers(payload.take(), req.headers())), limit: 262_144, length: len, fut: None, @@ -344,7 +322,7 @@ where fn err(e: PayloadError) -> Self { HttpMessageBody { - stream: dev::Payload::None, + stream: None, limit: 262_144, fut: None, err: Some(e), @@ -353,10 +331,7 @@ where } } -impl

Future for HttpMessageBody

-where - P: Stream + 'static, -{ +impl Future for HttpMessageBody { type Item = Bytes; type Error = PayloadError; @@ -378,7 +353,9 @@ where // future let limit = self.limit; self.fut = Some(Box::new( - std::mem::replace(&mut self.stream, actix_http::Payload::None) + self.stream + .take() + .unwrap() .from_err() .fold(BytesMut::with_capacity(8192), move |mut body, chunk| { if (body.len() + chunk.len()) > limit { diff --git a/src/types/query.rs b/src/types/query.rs index 0d37c45f..0467ddee 100644 --- a/src/types/query.rs +++ b/src/types/query.rs @@ -111,7 +111,7 @@ impl fmt::Display for Query { /// .route(web::get().to(index))); // <- use `Query` extractor /// } /// ``` -impl FromRequest

for Query +impl FromRequest for Query where T: de::DeserializeOwned, { @@ -119,7 +119,7 @@ where type Future = Result; #[inline] - fn from_request(req: &HttpRequest, _: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { serde_urlencoded::from_str::(req.query_string()) .map(|val| Ok(Query(val))) .unwrap_or_else(|e| { diff --git a/src/web.rs b/src/web.rs index 94c98c22..a354222c 100644 --- a/src/web.rs +++ b/src/web.rs @@ -50,7 +50,7 @@ pub use crate::types::*; /// ); /// } /// ``` -pub fn resource(path: &str) -> Resource

{ +pub fn resource(path: &str) -> Resource { Resource::new(path) } @@ -77,12 +77,12 @@ pub fn resource(path: &str) -> Resource

{ /// * /{project_id}/path2 /// * /{project_id}/path3 /// -pub fn scope(path: &str) -> Scope

{ +pub fn scope(path: &str) -> Scope { Scope::new(path) } /// Create *route* without configuration. -pub fn route() -> Route

{ +pub fn route() -> Route { Route::new() } @@ -102,7 +102,7 @@ pub fn route() -> Route

{ /// In the above example, one `GET` route get added: /// * /{project_id} /// -pub fn get() -> Route

{ +pub fn get() -> Route { Route::new().method(Method::GET) } @@ -122,7 +122,7 @@ pub fn get() -> Route

{ /// In the above example, one `POST` route get added: /// * /{project_id} /// -pub fn post() -> Route

{ +pub fn post() -> Route { Route::new().method(Method::POST) } @@ -142,7 +142,7 @@ pub fn post() -> Route

{ /// In the above example, one `PUT` route get added: /// * /{project_id} /// -pub fn put() -> Route

{ +pub fn put() -> Route { Route::new().method(Method::PUT) } @@ -162,7 +162,7 @@ pub fn put() -> Route

{ /// In the above example, one `PATCH` route get added: /// * /{project_id} /// -pub fn patch() -> Route

{ +pub fn patch() -> Route { Route::new().method(Method::PATCH) } @@ -182,7 +182,7 @@ pub fn patch() -> Route

{ /// In the above example, one `DELETE` route get added: /// * /{project_id} /// -pub fn delete() -> Route

{ +pub fn delete() -> Route { Route::new().method(Method::DELETE) } @@ -202,7 +202,7 @@ pub fn delete() -> Route

{ /// In the above example, one `HEAD` route get added: /// * /{project_id} /// -pub fn head() -> Route

{ +pub fn head() -> Route { Route::new().method(Method::HEAD) } @@ -222,7 +222,7 @@ pub fn head() -> Route

{ /// In the above example, one `GET` route get added: /// * /{project_id} /// -pub fn method(method: Method) -> Route

{ +pub fn method(method: Method) -> Route { Route::new().method(method) } @@ -240,10 +240,10 @@ pub fn method(method: Method) -> Route

{ /// web::to(index)) /// ); /// ``` -pub fn to(handler: F) -> Route

+pub fn to(handler: F) -> Route where F: Factory + 'static, - I: FromRequest

+ 'static, + I: FromRequest + 'static, R: Responder + 'static, { Route::new().to(handler) @@ -263,10 +263,10 @@ where /// web::to_async(index)) /// ); /// ``` -pub fn to_async(handler: F) -> Route

+pub fn to_async(handler: F) -> Route where F: AsyncFactory, - I: FromRequest

+ 'static, + I: FromRequest + 'static, R: IntoFuture + 'static, R::Item: Into, R::Error: Into, diff --git a/tests/test_server.rs b/tests/test_server.rs index 597e6930..3ec20bce 100644 --- a/tests/test_server.rs +++ b/tests/test_server.rs @@ -19,9 +19,7 @@ use rand::{distributions::Alphanumeric, Rng}; use actix_web::{http, test, web, App, HttpResponse, HttpServer}; #[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] -use actix_web::middleware::encoding; -#[cfg(any(feature = "brotli", feature = "flate2-zlib", feature = "flate2-rust"))] -use actix_web::middleware::encoding::BodyEncoding; +use actix_web::middleware::{BodyEncoding, Compress}; const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \ @@ -68,7 +66,7 @@ fn test_body_gzip() { let mut srv = TestServer::new(|| { h1::H1Service::new( App::new() - .wrap(encoding::Compress::new(ContentEncoding::Gzip)) + .wrap(Compress::new(ContentEncoding::Gzip)) .service(web::resource("/").route(web::to(|| Response::Ok().body(STR)))), ) }); @@ -99,13 +97,11 @@ fn test_body_encoding_override() { let mut srv = TestServer::new(|| { h1::H1Service::new( App::new() - .wrap(encoding::Compress::new(ContentEncoding::Gzip)) + .wrap(Compress::new(ContentEncoding::Gzip)) .service(web::resource("/").route(web::to(|| { - use actix_web::middleware::encoding::BodyEncoding; Response::Ok().encoding(ContentEncoding::Deflate).body(STR) }))) .service(web::resource("/raw").route(web::to(|| { - use actix_web::middleware::encoding::BodyEncoding; let body = actix_web::dev::Body::Bytes(STR.into()); let mut response = Response::with_body(actix_web::http::StatusCode::OK, body); @@ -168,7 +164,7 @@ fn test_body_gzip_large() { let data = srv_data.clone(); h1::H1Service::new( App::new() - .wrap(encoding::Compress::new(ContentEncoding::Gzip)) + .wrap(Compress::new(ContentEncoding::Gzip)) .service( web::resource("/") .route(web::to(move || Response::Ok().body(data.clone()))), @@ -209,7 +205,7 @@ fn test_body_gzip_large_random() { let data = srv_data.clone(); h1::H1Service::new( App::new() - .wrap(encoding::Compress::new(ContentEncoding::Gzip)) + .wrap(Compress::new(ContentEncoding::Gzip)) .service( web::resource("/") .route(web::to(move || Response::Ok().body(data.clone()))), @@ -244,7 +240,7 @@ fn test_body_chunked_implicit() { let mut srv = TestServer::new(move || { h1::H1Service::new( App::new() - .wrap(encoding::Compress::new(ContentEncoding::Gzip)) + .wrap(Compress::new(ContentEncoding::Gzip)) .service(web::resource("/").route(web::get().to(move || { Response::Ok().streaming(once(Ok::<_, Error>(Bytes::from_static( STR.as_ref(), @@ -281,15 +277,12 @@ fn test_body_chunked_implicit() { #[cfg(feature = "brotli")] fn test_body_br_streaming() { let mut srv = TestServer::new(move || { - h1::H1Service::new( - App::new() - .wrap(encoding::Compress::new(ContentEncoding::Br)) - .service(web::resource("/").route(web::to(move || { - Response::Ok().streaming(once(Ok::<_, Error>(Bytes::from_static( - STR.as_ref(), - )))) - }))), - ) + h1::H1Service::new(App::new().wrap(Compress::new(ContentEncoding::Br)).service( + web::resource("/").route(web::to(move || { + Response::Ok() + .streaming(once(Ok::<_, Error>(Bytes::from_static(STR.as_ref())))) + })), + )) }); let mut response = srv @@ -361,7 +354,7 @@ fn test_body_deflate() { let mut srv = TestServer::new(move || { h1::H1Service::new( App::new() - .wrap(encoding::Compress::new(ContentEncoding::Deflate)) + .wrap(Compress::new(ContentEncoding::Deflate)) .service( web::resource("/").route(web::to(move || Response::Ok().body(STR))), ), @@ -392,13 +385,9 @@ fn test_body_deflate() { #[cfg(any(feature = "brotli"))] fn test_body_brotli() { let mut srv = TestServer::new(move || { - h1::H1Service::new( - App::new() - .wrap(encoding::Compress::new(ContentEncoding::Br)) - .service( - web::resource("/").route(web::to(move || Response::Ok().body(STR))), - ), - ) + h1::H1Service::new(App::new().wrap(Compress::new(ContentEncoding::Br)).service( + web::resource("/").route(web::to(move || Response::Ok().body(STR))), + )) }); // client request @@ -427,7 +416,7 @@ fn test_body_brotli() { fn test_encoding() { let mut srv = TestServer::new(move || { HttpService::new( - App::new().enable_encoding().service( + App::new().wrap(Compress::default()).service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -456,7 +445,7 @@ fn test_encoding() { fn test_gzip_encoding() { let mut srv = TestServer::new(move || { HttpService::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -486,7 +475,7 @@ fn test_gzip_encoding_large() { let data = STR.repeat(10); let mut srv = TestServer::new(move || { h1::H1Service::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -520,7 +509,7 @@ fn test_reading_gzip_encoding_large_random() { let mut srv = TestServer::new(move || { HttpService::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -550,7 +539,7 @@ fn test_reading_gzip_encoding_large_random() { fn test_reading_deflate_encoding() { let mut srv = TestServer::new(move || { h1::H1Service::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -580,7 +569,7 @@ fn test_reading_deflate_encoding_large() { let data = STR.repeat(10); let mut srv = TestServer::new(move || { h1::H1Service::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -614,7 +603,7 @@ fn test_reading_deflate_encoding_large_random() { let mut srv = TestServer::new(move || { h1::H1Service::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -644,7 +633,7 @@ fn test_reading_deflate_encoding_large_random() { fn test_brotli_encoding() { let mut srv = TestServer::new(move || { h1::H1Service::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ), @@ -674,7 +663,7 @@ fn test_brotli_encoding_large() { let data = STR.repeat(10); let mut srv = TestServer::new(move || { h1::H1Service::new( - App::new().chain(encoding::Decompress::new()).service( + App::new().service( web::resource("/") .route(web::to(move |body: Bytes| Response::Ok().body(body))), ),