1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-13 05:43:57 +02:00

Compare commits

..

8 Commits

74 changed files with 354 additions and 268 deletions

View File

@ -1,15 +1,19 @@
# Changes # Changes
## [1.0.4] - TBD ## [1.0.4] - 2019-07-17
### Added ### Added
* Add `Responder` impl for `(T, StatusCode) where T: Responder` * Add `Responder` impl for `(T, StatusCode) where T: Responder`
* Allow to access app's resource map via
`ServiceRequest::resource_map()` and `HttpRequest::resource_map()` methods.
### Changed ### Changed
* Upgrade `rand` dependency version to 0.7 * Upgrade `rand` dependency version to 0.7
## [1.0.3] - 2019-06-28 ## [1.0.3] - 2019-06-28
### Added ### Added

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-web" name = "actix-web"
version = "1.0.3" version = "1.0.4"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust." description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
readme = "README.md" readme = "README.md"
@ -71,11 +71,11 @@ rust-tls = ["rustls", "actix-server/rust-tls"]
[dependencies] [dependencies]
actix-codec = "0.1.2" actix-codec = "0.1.2"
actix-service = "0.4.1" actix-service = "0.4.1"
actix-utils = "0.4.2" actix-utils = "0.4.4"
actix-router = "0.1.5" actix-router = "0.1.5"
actix-rt = "0.2.3" actix-rt = "0.2.4"
actix-web-codegen = "0.1.2" actix-web-codegen = "0.1.2"
actix-http = "0.2.5" actix-http = "0.2.6"
actix-server = "0.5.1" actix-server = "0.5.1"
actix-server-config = "0.1.1" actix-server-config = "0.1.1"
actix-threadpool = "0.1.1" actix-threadpool = "0.1.1"
@ -89,7 +89,7 @@ hashbrown = "0.5.0"
log = "0.4" log = "0.4"
mime = "0.3" mime = "0.3"
net2 = "0.2.33" net2 = "0.2.33"
parking_lot = "0.8" parking_lot = "0.9"
regex = "1.0" regex = "1.0"
serde = { version = "1.0", features=["derive"] } serde = { version = "1.0", features=["derive"] }
serde_json = "1.0" serde_json = "1.0"

View File

@ -1,3 +1,4 @@
#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)]
//! Cross-origin resource sharing (CORS) for Actix applications //! Cross-origin resource sharing (CORS) for Actix applications
//! //!
//! CORS middleware could be used with application and with resource. //! CORS middleware could be used with application and with resource.
@ -162,6 +163,7 @@ impl<T> AllOrSome<T> {
/// .max_age(3600); /// .max_age(3600);
/// # } /// # }
/// ``` /// ```
#[derive(Default)]
pub struct Cors { pub struct Cors {
cors: Option<Inner>, cors: Option<Inner>,
methods: bool, methods: bool,
@ -585,10 +587,10 @@ impl Inner {
} }
Err(CorsError::BadOrigin) Err(CorsError::BadOrigin)
} else { } else {
return match self.origins { match self.origins {
AllOrSome::All => Ok(()), AllOrSome::All => Ok(()),
_ => Err(CorsError::MissingOrigin), _ => Err(CorsError::MissingOrigin),
}; }
} }
} }
@ -663,7 +665,7 @@ impl Inner {
} }
Err(CorsError::BadRequestHeaders) Err(CorsError::BadRequestHeaders)
} else { } else {
return Ok(()); Ok(())
} }
} }
} }
@ -681,7 +683,7 @@ where
type Error = Error; type Error = Error;
type Future = Either< type Future = Either<
FutureResult<Self::Response, Error>, FutureResult<Self::Response, Error>,
Either<S::Future, Box<Future<Item = Self::Response, Error = Error>>>, Either<S::Future, Box<dyn Future<Item = Self::Response, Error = Error>>>,
>; >;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {

View File

@ -1,3 +1,5 @@
#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)]
//! Static files support //! Static files support
use std::cell::RefCell; use std::cell::RefCell;
use std::fmt::Write; use std::fmt::Write;
@ -50,14 +52,14 @@ pub struct ChunkedReadFile {
size: u64, size: u64,
offset: u64, offset: u64,
file: Option<File>, file: Option<File>,
fut: Option<Box<Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>, fut: Option<Box<dyn Future<Item = (File, Bytes), Error = BlockingError<io::Error>>>>,
counter: u64, counter: u64,
} }
fn handle_error(err: BlockingError<io::Error>) -> Error { fn handle_error(err: BlockingError<io::Error>) -> Error {
match err { match err {
BlockingError::Error(err) => err.into(), BlockingError::Error(err) => err.into(),
BlockingError::Canceled => ErrorInternalServerError("Unexpected error").into(), BlockingError::Canceled => ErrorInternalServerError("Unexpected error"),
} }
} }
@ -105,7 +107,7 @@ impl Stream for ChunkedReadFile {
} }
type DirectoryRenderer = type DirectoryRenderer =
Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>; dyn Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>;
/// A directory; responds with the generated directory listing. /// A directory; responds with the generated directory listing.
#[derive(Debug)] #[derive(Debug)]
@ -209,7 +211,7 @@ fn directory_listing(
)) ))
} }
type MimeOverride = Fn(&mime::Name) -> DispositionType; type MimeOverride = dyn Fn(&mime::Name) -> DispositionType;
/// Static files handling /// Static files handling
/// ///
@ -370,7 +372,7 @@ impl NewService for Files {
type Error = Error; type Error = Error;
type Service = FilesService; type Service = FilesService;
type InitError = (); type InitError = ();
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>; type Future = Box<dyn Future<Item = Self::Service, Error = Self::InitError>>;
fn new_service(&self, _: &()) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
let mut srv = FilesService { let mut srv = FilesService {
@ -416,7 +418,7 @@ impl FilesService {
req: ServiceRequest, req: ServiceRequest,
) -> Either< ) -> Either<
FutureResult<ServiceResponse, Error>, FutureResult<ServiceResponse, Error>,
Box<Future<Item = ServiceResponse, Error = Error>>, Box<dyn Future<Item = ServiceResponse, Error = Error>>,
> { > {
log::debug!("Files: Failed to handle {}: {}", req.path(), e); log::debug!("Files: Failed to handle {}: {}", req.path(), e);
if let Some(ref mut default) = self.default { if let Some(ref mut default) = self.default {
@ -433,7 +435,7 @@ impl Service for FilesService {
type Error = Error; type Error = Error;
type Future = Either< type Future = Either<
FutureResult<Self::Response, Self::Error>, FutureResult<Self::Response, Self::Error>,
Box<Future<Item = Self::Response, Error = Self::Error>>, Box<dyn Future<Item = Self::Response, Error = Self::Error>>,
>; >;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
@ -473,7 +475,7 @@ impl Service for FilesService {
Err(e) => ServiceResponse::from_err(e, req), Err(e) => ServiceResponse::from_err(e, req),
})) }))
} }
Err(e) => return self.handle_err(e, req), Err(e) => self.handle_err(e, req),
} }
} else if self.show_index { } else if self.show_index {
let dir = Directory::new(self.directory.clone(), path); let dir = Directory::new(self.directory.clone(), path);
@ -481,7 +483,7 @@ impl Service for FilesService {
let x = (self.renderer)(&dir, &req); let x = (self.renderer)(&dir, &req);
match x { match x {
Ok(resp) => Either::A(ok(resp)), Ok(resp) => Either::A(ok(resp)),
Err(e) => return Either::A(ok(ServiceResponse::from_err(e, req))), Err(e) => Either::A(ok(ServiceResponse::from_err(e, req))),
} }
} else { } else {
Either::A(ok(ServiceResponse::from_err( Either::A(ok(ServiceResponse::from_err(
@ -855,7 +857,7 @@ mod tests {
#[test] #[test]
fn test_named_file_content_length_headers() { fn test_named_file_content_length_headers() {
use actix_web::body::{MessageBody, ResponseBody}; // use actix_web::body::{MessageBody, ResponseBody};
let mut srv = test::init_service( let mut srv = test::init_service(
App::new().service(Files::new("test", ".").index_file("tests/test.binary")), App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
@ -866,7 +868,7 @@ mod tests {
.uri("/t%65st/tests/test.binary") .uri("/t%65st/tests/test.binary")
.header(header::RANGE, "bytes=10-20") .header(header::RANGE, "bytes=10-20")
.to_request(); .to_request();
let response = test::call_service(&mut srv, request); let _response = test::call_service(&mut srv, request);
// let contentlength = response // let contentlength = response
// .headers() // .headers()
@ -889,7 +891,7 @@ mod tests {
.uri("/t%65st/tests/test.binary") .uri("/t%65st/tests/test.binary")
// .no_default_headers() // .no_default_headers()
.to_request(); .to_request();
let response = test::call_service(&mut srv, request); let _response = test::call_service(&mut srv, request);
// let contentlength = response // let contentlength = response
// .headers() // .headers()
@ -937,7 +939,7 @@ mod tests {
.method(Method::HEAD) .method(Method::HEAD)
.uri("/t%65st/tests/test.binary") .uri("/t%65st/tests/test.binary")
.to_request(); .to_request();
let response = test::call_service(&mut srv, request); let _response = test::call_service(&mut srv, request);
// TODO: fix check // TODO: fix check
// let contentlength = response // let contentlength = response

View File

@ -24,8 +24,8 @@ use crate::ChunkedReadFile;
bitflags! { bitflags! {
pub(crate) struct Flags: u32 { pub(crate) struct Flags: u32 {
const ETAG = 0b00000001; const ETAG = 0b0000_0001;
const LAST_MD = 0b00000010; const LAST_MD = 0b0000_0010;
} }
} }
@ -311,8 +311,8 @@ impl Responder for NamedFile {
return Ok(resp.streaming(reader)); return Ok(resp.streaming(reader));
} }
match req.method() { match *req.method() {
&Method::HEAD | &Method::GET => (), Method::HEAD | Method::GET => (),
_ => { _ => {
return Ok(HttpResponse::MethodNotAllowed() return Ok(HttpResponse::MethodNotAllowed()
.header(header::CONTENT_TYPE, "text/plain") .header(header::CONTENT_TYPE, "text/plain")

View File

@ -5,7 +5,7 @@ pub struct HttpRange {
pub length: u64, pub length: u64,
} }
static PREFIX: &'static str = "bytes="; static PREFIX: &str = "bytes=";
const PREFIX_LEN: usize = 6; const PREFIX_LEN: usize = 6;
impl HttpRange { impl HttpRange {

View File

@ -13,7 +13,7 @@ use crate::helpers::{BoxedHttpNewService, BoxedHttpService, HttpNewService};
use crate::request::FramedRequest; use crate::request::FramedRequest;
use crate::state::State; use crate::state::State;
type BoxedResponse = Box<Future<Item = (), Error = Error>>; type BoxedResponse = Box<dyn Future<Item = (), Error = Error>>;
pub trait HttpServiceFactory { pub trait HttpServiceFactory {
type Factory: NewService; type Factory: NewService;
@ -61,7 +61,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
Request = FramedRequest<T, S>, Request = FramedRequest<T, S>,
Response = (), Response = (),
Error = Error, Error = Error,
Future = Box<Future<Item = (), Error = Error>>, Future = Box<dyn Future<Item = (), Error = Error>>,
>, >,
{ {
let path = factory.path().to_string(); let path = factory.path().to_string();
@ -129,7 +129,7 @@ pub struct CreateService<T, S> {
enum CreateServiceItem<T, S> { enum CreateServiceItem<T, S> {
Future( Future(
Option<String>, Option<String>,
Box<Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>, Box<dyn Future<Item = BoxedHttpService<FramedRequest<T, S>>, Error = ()>>,
), ),
Service(String, BoxedHttpService<FramedRequest<T, S>>), Service(String, BoxedHttpService<FramedRequest<T, S>>),
} }

View File

@ -3,23 +3,23 @@ use actix_service::{NewService, Service};
use futures::{Future, Poll}; use futures::{Future, Poll};
pub(crate) type BoxedHttpService<Req> = Box< pub(crate) type BoxedHttpService<Req> = Box<
Service< dyn Service<
Request = Req, Request = Req,
Response = (), Response = (),
Error = Error, Error = Error,
Future = Box<Future<Item = (), Error = Error>>, Future = Box<dyn Future<Item = (), Error = Error>>,
>, >,
>; >;
pub(crate) type BoxedHttpNewService<Req> = Box< pub(crate) type BoxedHttpNewService<Req> = Box<
NewService< dyn NewService<
Config = (), Config = (),
Request = Req, Request = Req,
Response = (), Response = (),
Error = Error, Error = Error,
InitError = (), InitError = (),
Service = BoxedHttpService<Req>, Service = BoxedHttpService<Req>,
Future = Box<Future<Item = BoxedHttpService<Req>, Error = ()>>, Future = Box<dyn Future<Item = BoxedHttpService<Req>, Error = ()>>,
>, >,
>; >;
@ -30,7 +30,7 @@ where
T: NewService<Response = (), Error = Error>, T: NewService<Response = (), Error = Error>,
T::Response: 'static, T::Response: 'static,
T::Future: 'static, T::Future: 'static,
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static, T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
{ {
pub fn new(service: T) -> Self { pub fn new(service: T) -> Self {
@ -43,7 +43,7 @@ where
T: NewService<Config = (), Response = (), Error = Error>, T: NewService<Config = (), Response = (), Error = Error>,
T::Request: 'static, T::Request: 'static,
T::Future: 'static, T::Future: 'static,
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static, T::Service: Service<Future = Box<dyn Future<Item = (), Error = Error>>> + 'static,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
{ {
type Config = (); type Config = ();
@ -52,7 +52,7 @@ where
type Error = Error; type Error = Error;
type InitError = (); type InitError = ();
type Service = BoxedHttpService<T::Request>; type Service = BoxedHttpService<T::Request>;
type Future = Box<Future<Item = Self::Service, Error = ()>>; type Future = Box<dyn Future<Item = Self::Service, Error = ()>>;
fn new_service(&self, _: &()) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| { Box::new(self.0.new_service(&()).map_err(|_| ()).and_then(|service| {
@ -70,7 +70,7 @@ impl<T> Service for HttpServiceWrapper<T>
where where
T: Service< T: Service<
Response = (), Response = (),
Future = Box<Future<Item = (), Error = Error>>, Future = Box<dyn Future<Item = (), Error = Error>>,
Error = Error, Error = Error,
>, >,
T::Request: 'static, T::Request: 'static,
@ -78,7 +78,7 @@ where
type Request = T::Request; type Request = T::Request;
type Response = (); type Response = ();
type Error = Error; type Error = Error;
type Future = Box<Future<Item = (), Error = Error>>; type Future = Box<dyn Future<Item = (), Error = Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready() self.service.poll_ready()

View File

@ -1,3 +1,9 @@
#![allow(
clippy::type_complexity,
clippy::new_without_default,
dead_code,
deprecated
)]
mod app; mod app;
mod helpers; mod helpers;
mod request; mod request;

View File

@ -140,7 +140,7 @@ where
type Request = FramedRequest<Io, S>; type Request = FramedRequest<Io, S>;
type Response = (); type Response = ();
type Error = Error; type Error = Error;
type Future = Box<Future<Item = (), Error = Error>>; type Future = Box<dyn Future<Item = (), Error = Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(())) Ok(Async::Ready(()))

View File

@ -1,11 +1,14 @@
# Changes # Changes
## [0.2.6] - TBD ## [0.2.6] - 2019-07-17
### Changed ### Changed
* Replace `ClonableService` with local copy
* Upgrade `rand` dependency version to 0.7 * Upgrade `rand` dependency version to 0.7
## [0.2.5] - 2019-06-28 ## [0.2.5] - 2019-06-28
### Added ### Added

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-http" name = "actix-http"
version = "0.2.5" version = "0.2.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http primitives" description = "Actix http primitives"
readme = "README.md" readme = "README.md"
@ -46,10 +46,10 @@ secure-cookies = ["ring"]
[dependencies] [dependencies]
actix-service = "0.4.1" actix-service = "0.4.1"
actix-codec = "0.1.2" actix-codec = "0.1.2"
actix-connect = "0.2.0" actix-connect = "0.2.1"
actix-utils = "0.4.2" actix-utils = "0.4.4"
actix-server-config = "0.1.1" actix-server-config = "0.1.1"
actix-threadpool = "0.1.0" actix-threadpool = "0.1.1"
base64 = "0.10" base64 = "0.10"
bitflags = "1.0" bitflags = "1.0"

View File

@ -26,7 +26,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
client_disconnect: u64, client_disconnect: u64,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, S)>, _t: PhantomData<(T, S)>,
} }

View File

@ -94,7 +94,8 @@ where
T: AsyncRead + AsyncWrite + 'static, T: AsyncRead + AsyncWrite + 'static,
{ {
type Io = T; type Io = T;
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>; type Future =
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
fn protocol(&self) -> Protocol { fn protocol(&self) -> Protocol {
match self.io { match self.io {
@ -129,7 +130,7 @@ where
type TunnelFuture = Either< type TunnelFuture = Either<
Box< Box<
Future< dyn Future<
Item = (ResponseHead, Framed<Self::Io, ClientCodec>), Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
Error = SendRequestError, Error = SendRequestError,
>, >,
@ -169,7 +170,8 @@ where
B: AsyncRead + AsyncWrite + 'static, B: AsyncRead + AsyncWrite + 'static,
{ {
type Io = EitherIo<A, B>; type Io = EitherIo<A, B>;
type Future = Box<Future<Item = (ResponseHead, Payload), Error = SendRequestError>>; type Future =
Box<dyn Future<Item = (ResponseHead, Payload), Error = SendRequestError>>;
fn protocol(&self) -> Protocol { fn protocol(&self) -> Protocol {
match self { match self {
@ -190,7 +192,7 @@ where
} }
type TunnelFuture = Box< type TunnelFuture = Box<
Future< dyn Future<
Item = (ResponseHead, Framed<Self::Io, ClientCodec>), Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
Error = SendRequestError, Error = SendRequestError,
>, >,

View File

@ -47,6 +47,7 @@ pub struct Connector<T, U> {
} }
impl Connector<(), ()> { impl Connector<(), ()> {
#[allow(clippy::new_ret_no_self)]
pub fn new() -> Connector< pub fn new() -> Connector<
impl Service< impl Service<
Request = TcpConnect<Uri>, Request = TcpConnect<Uri>,

View File

@ -427,7 +427,9 @@ where
fn check_availibility(&self) { fn check_availibility(&self) {
if !self.waiters_queue.is_empty() && self.acquired < self.limit { if !self.waiters_queue.is_empty() && self.acquired < self.limit {
self.task.as_ref().map(|t| t.notify()); if let Some(t) = self.task.as_ref() {
t.notify()
}
} }
} }
} }

View File

@ -0,0 +1,42 @@
use std::cell::UnsafeCell;
use std::rc::Rc;
use actix_service::Service;
use futures::Poll;
#[doc(hidden)]
/// Service that allows to turn non-clone service to a service with `Clone` impl
pub(crate) struct CloneableService<T>(Rc<UnsafeCell<T>>);
impl<T> CloneableService<T> {
pub(crate) fn new(service: T) -> Self
where
T: Service,
{
Self(Rc::new(UnsafeCell::new(service)))
}
}
impl<T> Clone for CloneableService<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> Service for CloneableService<T>
where
T: Service,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Future = T::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
unsafe { &mut *self.0.as_ref().get() }.poll_ready()
}
fn call(&mut self, req: T::Request) -> Self::Future {
unsafe { &mut *self.0.as_ref().get() }.call(req)
}
}

View File

@ -104,6 +104,7 @@ impl CookieStr {
} }
} }
#[allow(clippy::ptr_arg)]
fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> { fn to_raw_str<'s, 'c: 's>(&'s self, string: &'s Cow<'c, str>) -> Option<&'c str> {
match *self { match *self {
CookieStr::Indexed(i, j) => match *string { CookieStr::Indexed(i, j) => match *string {

View File

@ -6,8 +6,8 @@ use ring::rand::{SecureRandom, SystemRandom};
use super::private::KEY_LEN as PRIVATE_KEY_LEN; use super::private::KEY_LEN as PRIVATE_KEY_LEN;
use super::signed::KEY_LEN as SIGNED_KEY_LEN; use super::signed::KEY_LEN as SIGNED_KEY_LEN;
static HKDF_DIGEST: &'static Algorithm = &SHA256; static HKDF_DIGEST: &Algorithm = &SHA256;
const KEYS_INFO: &'static str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM"; const KEYS_INFO: &str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
/// A cryptographic master key for use with `Signed` and/or `Private` jars. /// A cryptographic master key for use with `Signed` and/or `Private` jars.
/// ///

View File

@ -10,7 +10,7 @@ use crate::cookie::{Cookie, CookieJar};
// Keep these in sync, and keep the key len synced with the `private` docs as // Keep these in sync, and keep the key len synced with the `private` docs as
// well as the `KEYS_INFO` const in secure::Key. // well as the `KEYS_INFO` const in secure::Key.
static ALGO: &'static Algorithm = &AES_256_GCM; static ALGO: &Algorithm = &AES_256_GCM;
const NONCE_LEN: usize = 12; const NONCE_LEN: usize = 12;
pub const KEY_LEN: usize = 32; pub const KEY_LEN: usize = 32;

View File

@ -6,7 +6,7 @@ use crate::cookie::{Cookie, CookieJar};
// Keep these in sync, and keep the key len synced with the `signed` docs as // Keep these in sync, and keep the key len synced with the `signed` docs as
// well as the `KEYS_INFO` const in secure::Key. // well as the `KEYS_INFO` const in secure::Key.
static HMAC_DIGEST: &'static Algorithm = &SHA256; static HMAC_DIGEST: &Algorithm = &SHA256;
const BASE64_DIGEST_LEN: usize = 44; const BASE64_DIGEST_LEN: usize = 44;
pub const KEY_LEN: usize = 32; pub const KEY_LEN: usize = 32;

View File

@ -43,12 +43,12 @@ pub type Result<T, E = Error> = result::Result<T, E>;
/// if you have access to an actix `Error` you can always get a /// if you have access to an actix `Error` you can always get a
/// `ResponseError` reference from it. /// `ResponseError` reference from it.
pub struct Error { pub struct Error {
cause: Box<ResponseError>, cause: Box<dyn ResponseError>,
} }
impl Error { impl Error {
/// Returns the reference to the underlying `ResponseError`. /// Returns the reference to the underlying `ResponseError`.
pub fn as_response_error(&self) -> &ResponseError { pub fn as_response_error(&self) -> &dyn ResponseError {
self.cause.as_ref() self.cause.as_ref()
} }
} }

View File

@ -6,7 +6,7 @@ use hashbrown::HashMap;
#[derive(Default)] #[derive(Default)]
/// A type map of request extensions. /// A type map of request extensions.
pub struct Extensions { pub struct Extensions {
map: HashMap<TypeId, Box<Any>>, map: HashMap<TypeId, Box<dyn Any>>,
} }
impl Extensions { impl Extensions {
@ -35,14 +35,14 @@ impl Extensions {
pub fn get<T: 'static>(&self) -> Option<&T> { pub fn get<T: 'static>(&self) -> Option<&T> {
self.map self.map
.get(&TypeId::of::<T>()) .get(&TypeId::of::<T>())
.and_then(|boxed| (&**boxed as &(Any + 'static)).downcast_ref()) .and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
} }
/// Get a mutable reference to a type previously inserted on this `Extensions`. /// Get a mutable reference to a type previously inserted on this `Extensions`.
pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> { pub fn get_mut<T: 'static>(&mut self) -> Option<&mut T> {
self.map self.map
.get_mut(&TypeId::of::<T>()) .get_mut(&TypeId::of::<T>())
.and_then(|boxed| (&mut **boxed as &mut (Any + 'static)).downcast_mut()) .and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
} }
/// Remove a type from this `Extensions`. /// Remove a type from this `Extensions`.
@ -50,7 +50,7 @@ impl Extensions {
/// If a extension of this type existed, it will be returned. /// If a extension of this type existed, it will be returned.
pub fn remove<T: 'static>(&mut self) -> Option<T> { pub fn remove<T: 'static>(&mut self) -> Option<T> {
self.map.remove(&TypeId::of::<T>()).and_then(|boxed| { self.map.remove(&TypeId::of::<T>()).and_then(|boxed| {
(boxed as Box<Any + 'static>) (boxed as Box<dyn Any + 'static>)
.downcast() .downcast()
.ok() .ok()
.map(|boxed| *boxed) .map(|boxed| *boxed)

View File

@ -502,15 +502,15 @@ impl ChunkedState {
fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> { fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> {
let radix = 16; let radix = 16;
match byte!(rdr) { match byte!(rdr) {
b @ b'0'...b'9' => { b @ b'0'..=b'9' => {
*size *= radix; *size *= radix;
*size += u64::from(b - b'0'); *size += u64::from(b - b'0');
} }
b @ b'a'...b'f' => { b @ b'a'..=b'f' => {
*size *= radix; *size *= radix;
*size += u64::from(b + 10 - b'a'); *size += u64::from(b + 10 - b'a');
} }
b @ b'A'...b'F' => { b @ b'A'..=b'F' => {
*size *= radix; *size *= radix;
*size += u64::from(b + 10 - b'A'); *size += u64::from(b + 10 - b'A');
} }

View File

@ -5,7 +5,6 @@ use std::{fmt, io, net};
use actix_codec::{Decoder, Encoder, Framed, FramedParts}; use actix_codec::{Decoder, Encoder, Framed, FramedParts};
use actix_server_config::IoStream; use actix_server_config::IoStream;
use actix_service::Service; use actix_service::Service;
use actix_utils::cloneable::CloneableService;
use bitflags::bitflags; use bitflags::bitflags;
use bytes::{BufMut, BytesMut}; use bytes::{BufMut, BytesMut};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
@ -13,6 +12,7 @@ use log::{error, trace};
use tokio_timer::Delay; use tokio_timer::Delay;
use crate::body::{Body, BodySize, MessageBody, ResponseBody}; use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService;
use crate::config::ServiceConfig; use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error}; use crate::error::{DispatchError, Error};
use crate::error::{ParseError, PayloadError}; use crate::error::{ParseError, PayloadError};

View File

@ -5,11 +5,11 @@ use std::rc::Rc;
use actix_codec::Framed; use actix_codec::Framed;
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig}; use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
use actix_service::{IntoNewService, NewService, Service}; use actix_service::{IntoNewService, NewService, Service};
use actix_utils::cloneable::CloneableService;
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream}; use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
use crate::body::MessageBody; use crate::body::MessageBody;
use crate::cloneable::CloneableService;
use crate::config::{KeepAlive, ServiceConfig}; use crate::config::{KeepAlive, ServiceConfig};
use crate::error::{DispatchError, Error, ParseError}; use crate::error::{DispatchError, Error, ParseError};
use crate::helpers::DataFactory; use crate::helpers::DataFactory;
@ -26,7 +26,7 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
cfg: ServiceConfig, cfg: ServiceConfig,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -108,7 +108,7 @@ where
/// Set on connect callback. /// Set on connect callback.
pub(crate) fn on_connect( pub(crate) fn on_connect(
mut self, mut self,
f: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>, f: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> Self { ) -> Self {
self.on_connect = f; self.on_connect = f;
self self
@ -174,7 +174,7 @@ where
fut_upg: Option<U::Future>, fut_upg: Option<U::Future>,
expect: Option<X::Service>, expect: Option<X::Service>,
upgrade: Option<U::Service>, upgrade: Option<U::Service>,
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: Option<ServiceConfig>, cfg: Option<ServiceConfig>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -233,7 +233,7 @@ pub struct H1ServiceHandler<T, P, S, B, X, U> {
srv: CloneableService<S>, srv: CloneableService<S>,
expect: CloneableService<X>, expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>, upgrade: Option<CloneableService<U>>,
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: ServiceConfig, cfg: ServiceConfig,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -254,12 +254,12 @@ where
srv: S, srv: S,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> H1ServiceHandler<T, P, S, B, X, U> { ) -> H1ServiceHandler<T, P, S, B, X, U> {
H1ServiceHandler { H1ServiceHandler {
srv: CloneableService::new(srv), srv: CloneableService::new(srv),
expect: CloneableService::new(expect), expect: CloneableService::new(expect),
upgrade: upgrade.map(|s| CloneableService::new(s)), upgrade: upgrade.map(CloneableService::new),
cfg, cfg,
on_connect, on_connect,
_t: PhantomData, _t: PhantomData,

View File

@ -6,7 +6,6 @@ use std::{fmt, mem, net};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_server_config::IoStream; use actix_server_config::IoStream;
use actix_service::Service; use actix_service::Service;
use actix_utils::cloneable::CloneableService;
use bitflags::bitflags; use bitflags::bitflags;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::{try_ready, Async, Future, Poll, Sink, Stream}; use futures::{try_ready, Async, Future, Poll, Sink, Stream};
@ -20,6 +19,7 @@ use log::{debug, error, trace};
use tokio_timer::Delay; use tokio_timer::Delay;
use crate::body::{Body, BodySize, MessageBody, ResponseBody}; use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService;
use crate::config::ServiceConfig; use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError}; use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
use crate::helpers::DataFactory; use crate::helpers::DataFactory;

View File

@ -5,7 +5,6 @@ use std::{io, net, rc};
use actix_codec::{AsyncRead, AsyncWrite, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig}; use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
use actix_service::{IntoNewService, NewService, Service}; use actix_service::{IntoNewService, NewService, Service};
use actix_utils::cloneable::CloneableService;
use bytes::Bytes; use bytes::Bytes;
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream}; use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
@ -14,6 +13,7 @@ use h2::RecvStream;
use log::error; use log::error;
use crate::body::MessageBody; use crate::body::MessageBody;
use crate::cloneable::CloneableService;
use crate::config::{KeepAlive, ServiceConfig}; use crate::config::{KeepAlive, ServiceConfig};
use crate::error::{DispatchError, Error, ParseError, ResponseError}; use crate::error::{DispatchError, Error, ParseError, ResponseError};
use crate::helpers::DataFactory; use crate::helpers::DataFactory;
@ -27,7 +27,7 @@ use super::dispatcher::Dispatcher;
pub struct H2Service<T, P, S, B> { pub struct H2Service<T, P, S, B> {
srv: S, srv: S,
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -64,7 +64,7 @@ where
/// Set on connect callback. /// Set on connect callback.
pub(crate) fn on_connect( pub(crate) fn on_connect(
mut self, mut self,
f: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> Self { ) -> Self {
self.on_connect = f; self.on_connect = f;
self self
@ -102,7 +102,7 @@ where
pub struct H2ServiceResponse<T, P, S: NewService, B> { pub struct H2ServiceResponse<T, P, S: NewService, B> {
fut: <S::Future as IntoFuture>::Future, fut: <S::Future as IntoFuture>::Future,
cfg: Option<ServiceConfig>, cfg: Option<ServiceConfig>,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -132,7 +132,7 @@ where
pub struct H2ServiceHandler<T, P, S, B> { pub struct H2ServiceHandler<T, P, S, B> {
srv: CloneableService<S>, srv: CloneableService<S>,
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -146,7 +146,7 @@ where
{ {
fn new( fn new(
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
srv: S, srv: S,
) -> H2ServiceHandler<T, P, S, B> { ) -> H2ServiceHandler<T, P, S, B> {
H2ServiceHandler { H2ServiceHandler {
@ -256,7 +256,7 @@ where
on_connect.take(), on_connect.take(),
config.take().unwrap(), config.take().unwrap(),
None, None,
peer_addr.clone(), *peer_addr,
)); ));
self.poll() self.poll()
} }

View File

@ -70,6 +70,7 @@ impl<'a> From<&'a str> for DispositionType {
/// assert_eq!(param.as_filename().unwrap(), "sample.txt"); /// assert_eq!(param.as_filename().unwrap(), "sample.txt");
/// ``` /// ```
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum DispositionParam { pub enum DispositionParam {
/// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from /// For [`DispositionType::FormData`] (i.e. *multipart/form-data*), the name of an field from
/// the form. /// the form.
@ -719,8 +720,10 @@ mod tests {
}; };
assert_eq!(a, b); assert_eq!(a, b);
let a = let a = HeaderValue::from_str(
HeaderValue::from_str("form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"").unwrap(); "form-data; name=upload; filename=\"余固知謇謇之為患兮,忍而不能舍也.pptx\"",
)
.unwrap();
let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap(); let a: ContentDisposition = ContentDisposition::from_raw(&a).unwrap();
let b = ContentDisposition { let b = ContentDisposition {
disposition: DispositionType::FormData, disposition: DispositionType::FormData,

View File

@ -1,8 +1,10 @@
//! Basic http primitives for actix-net framework. //! Basic http primitives for actix-net framework.
#![allow( #![allow(
clippy::type_complexity, clippy::type_complexity,
clippy::too_many_arguments,
clippy::new_without_default, clippy::new_without_default,
clippy::borrow_interior_mutable_const clippy::borrow_interior_mutable_const,
clippy::write_with_newline
)] )]
#[macro_use] #[macro_use]
@ -11,6 +13,7 @@ extern crate log;
pub mod body; pub mod body;
mod builder; mod builder;
pub mod client; pub mod client;
mod cloneable;
mod config; mod config;
pub mod encoding; pub mod encoding;
mod extensions; mod extensions;

View File

@ -385,6 +385,7 @@ impl Drop for BoxedResponseHead {
pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>); pub struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
#[doc(hidden)] #[doc(hidden)]
#[allow(clippy::vec_box)]
/// Request's objects pool /// Request's objects pool
pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>); pub struct BoxedResponsePool(RefCell<Vec<Box<ResponseHead>>>);

View File

@ -6,13 +6,13 @@ use actix_server_config::{
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig, Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
}; };
use actix_service::{IntoNewService, NewService, Service}; use actix_service::{IntoNewService, NewService, Service};
use actix_utils::cloneable::CloneableService;
use bytes::{Buf, BufMut, Bytes, BytesMut}; use bytes::{Buf, BufMut, Bytes, BytesMut};
use futures::{try_ready, Async, Future, IntoFuture, Poll}; use futures::{try_ready, Async, Future, IntoFuture, Poll};
use h2::server::{self, Handshake}; use h2::server::{self, Handshake};
use crate::body::MessageBody; use crate::body::MessageBody;
use crate::builder::HttpServiceBuilder; use crate::builder::HttpServiceBuilder;
use crate::cloneable::CloneableService;
use crate::config::{KeepAlive, ServiceConfig}; use crate::config::{KeepAlive, ServiceConfig};
use crate::error::{DispatchError, Error}; use crate::error::{DispatchError, Error};
use crate::helpers::DataFactory; use crate::helpers::DataFactory;
@ -26,7 +26,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
cfg: ServiceConfig, cfg: ServiceConfig,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -140,7 +140,7 @@ where
/// Set on connect callback. /// Set on connect callback.
pub(crate) fn on_connect( pub(crate) fn on_connect(
mut self, mut self,
f: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> Self { ) -> Self {
self.on_connect = f; self.on_connect = f;
self self
@ -196,7 +196,7 @@ pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewServ
fut_upg: Option<U::Future>, fut_upg: Option<U::Future>,
expect: Option<X::Service>, expect: Option<X::Service>,
upgrade: Option<U::Service>, upgrade: Option<U::Service>,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: Option<ServiceConfig>, cfg: Option<ServiceConfig>,
_t: PhantomData<(T, P, B)>, _t: PhantomData<(T, P, B)>,
} }
@ -257,7 +257,7 @@ pub struct HttpServiceHandler<T, P, S, B, X, U> {
expect: CloneableService<X>, expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>, upgrade: Option<CloneableService<U>>,
cfg: ServiceConfig, cfg: ServiceConfig,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B, X)>, _t: PhantomData<(T, P, B, X)>,
} }
@ -278,14 +278,14 @@ where
srv: S, srv: S,
expect: X, expect: X,
upgrade: Option<U>, upgrade: Option<U>,
on_connect: Option<rc::Rc<Fn(&T) -> Box<dyn DataFactory>>>, on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> HttpServiceHandler<T, P, S, B, X, U> { ) -> HttpServiceHandler<T, P, S, B, X, U> {
HttpServiceHandler { HttpServiceHandler {
cfg, cfg,
on_connect, on_connect,
srv: CloneableService::new(srv), srv: CloneableService::new(srv),
expect: CloneableService::new(expect), expect: CloneableService::new(expect),
upgrade: upgrade.map(|s| CloneableService::new(s)), upgrade: upgrade.map(CloneableService::new),
_t: PhantomData, _t: PhantomData,
} }
} }

View File

@ -47,10 +47,7 @@ impl Into<u8> for OpCode {
Ping => 9, Ping => 9,
Pong => 10, Pong => 10,
Bad => { Bad => {
debug_assert!( log::error!("Attempted to convert invalid opcode to u8. This is a bug.");
false,
"Attempted to convert invalid opcode to u8. This is a bug."
);
8 // if this somehow happens, a close frame will help us tear down quickly 8 // if this somehow happens, a close frame will help us tear down quickly
} }
} }
@ -206,7 +203,7 @@ impl<T: Into<String>> From<(CloseCode, T)> for CloseReason {
} }
} }
static WS_GUID: &'static str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; static WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
// TODO: hash is always same size, we dont need String // TODO: hash is always same size, we dont need String
pub fn hash_key(key: &[u8]) -> String { pub fn hash_key(key: &[u8]) -> String {

View File

@ -261,7 +261,7 @@ where
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.borrow_mut().poll_ready() self.service.borrow_mut().poll_ready()
@ -283,7 +283,7 @@ where
res.request().extensions_mut().remove::<IdentityItem>(); res.request().extensions_mut().remove::<IdentityItem>();
if let Some(id) = id { if let Some(id) = id {
return Either::A( Either::A(
backend backend
.to_response(id.id, id.changed, &mut res) .to_response(id.id, id.changed, &mut res)
.into_future() .into_future()
@ -291,7 +291,7 @@ where
Ok(_) => Ok(res), Ok(_) => Ok(res),
Err(e) => Ok(res.error_response(e)), Err(e) => Ok(res.error_response(e)),
}), }),
); )
} else { } else {
Either::B(ok(res)) Either::B(ok(res))
} }
@ -333,8 +333,7 @@ struct CookieIdentityExtention {
impl CookieIdentityInner { impl CookieIdentityInner {
fn new(key: &[u8]) -> CookieIdentityInner { fn new(key: &[u8]) -> CookieIdentityInner {
let key_v2: Vec<u8> = let key_v2: Vec<u8> = key.iter().chain([1, 0, 0, 0].iter()).cloned().collect();
key.iter().chain([1, 0, 0, 0].iter()).map(|e| *e).collect();
CookieIdentityInner { CookieIdentityInner {
key: Key::from_master(key), key: Key::from_master(key),
key_v2: Key::from_master(&key_v2), key_v2: Key::from_master(&key_v2),
@ -585,13 +584,14 @@ impl IdentityPolicy for CookieIdentityPolicy {
) )
} else if self.0.always_update_cookie() && id.is_some() { } else if self.0.always_update_cookie() && id.is_some() {
let visit_timestamp = SystemTime::now(); let visit_timestamp = SystemTime::now();
let mut login_timestamp = None; let login_timestamp = if self.0.requires_oob_data() {
if self.0.requires_oob_data() {
let CookieIdentityExtention { let CookieIdentityExtention {
login_timestamp: lt, login_timestamp: lt,
} = res.request().extensions_mut().remove().unwrap(); } = res.request().extensions_mut().remove().unwrap();
login_timestamp = lt; lt
} } else {
None
};
self.0.set_cookie( self.0.set_cookie(
res, res,
Some(CookieValue { Some(CookieValue {

View File

@ -1,3 +1,5 @@
#![allow(clippy::borrow_interior_mutable_const)]
mod error; mod error;
mod extractor; mod extractor;
mod server; mod server;

View File

@ -418,7 +418,7 @@ impl Stream for Field {
inner.poll(&self.safety) inner.poll(&self.safety)
} else if !self.safety.is_clean() { } else if !self.safety.is_clean() {
return Err(MultipartError::NotConsumed); Err(MultipartError::NotConsumed)
} else { } else {
Ok(Async::NotReady) Ok(Async::NotReady)
} }
@ -533,11 +533,9 @@ impl InnerField {
let b_size = boundary.len() + b_len; let b_size = boundary.len() + b_len;
if len < b_size { if len < b_size {
return Ok(Async::NotReady); return Ok(Async::NotReady);
} else { } else if &payload.buf[b_len..b_size] == boundary.as_bytes() {
if &payload.buf[b_len..b_size] == boundary.as_bytes() { // found boundary
// found boundary return Ok(Async::Ready(None));
return Ok(Async::Ready(None));
}
} }
} }
} }
@ -557,7 +555,7 @@ impl InnerField {
// check boundary // check boundary
if (&payload.buf[cur..cur + 2] == b"\r\n" if (&payload.buf[cur..cur + 2] == b"\r\n"
&& &payload.buf[cur + 2..cur + 4] == b"--") && &payload.buf[cur + 2..cur + 4] == b"--")
|| (&payload.buf[cur..cur + 1] == b"\r" || (&payload.buf[cur..=cur] == b"\r"
&& &payload.buf[cur + 1..cur + 3] == b"--") && &payload.buf[cur + 1..cur + 3] == b"--")
{ {
if cur != 0 { if cur != 0 {

View File

@ -309,7 +309,7 @@ where
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = S::Error; type Error = S::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready() self.service.poll_ready()
@ -342,7 +342,7 @@ where
} }
} }
(SessionStatus::Purged, _) => { (SessionStatus::Purged, _) => {
inner.remove_cookie(&mut res); let _ = inner.remove_cookie(&mut res);
res res
} }
_ => res, _ => res,

View File

@ -282,7 +282,7 @@ mod tests {
#[test] #[test]
fn purge_session() { fn purge_session() {
let mut req = test::TestRequest::default().to_srv_request(); let req = test::TestRequest::default().to_srv_request();
let session = Session::get_session(&mut *req.extensions_mut()); let session = Session::get_session(&mut *req.extensions_mut());
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged); assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
session.purge(); session.purge();
@ -291,7 +291,7 @@ mod tests {
#[test] #[test]
fn renew_session() { fn renew_session() {
let mut req = test::TestRequest::default().to_srv_request(); let req = test::TestRequest::default().to_srv_request();
let session = Session::get_session(&mut *req.extensions_mut()); let session = Session::get_session(&mut *req.extensions_mut());
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged); assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
session.renew(); session.renew();

View File

@ -1,3 +1,4 @@
#![allow(clippy::borrow_interior_mutable_const)]
//! Actix actors integration for Actix web framework //! Actix actors integration for Actix web framework
mod context; mod context;
pub mod ws; pub mod ws;

View File

@ -435,7 +435,7 @@ where
} }
} }
Frame::Binary(data) => Message::Binary( Frame::Binary(data) => Message::Binary(
data.map(|b| b.freeze()).unwrap_or_else(|| Bytes::new()), data.map(|b| b.freeze()).unwrap_or_else(Bytes::new),
), ),
Frame::Ping(s) => Message::Ping(s), Frame::Ping(s) => Message::Ping(s),
Frame::Pong(s) => Message::Pong(s), Frame::Pong(s) => Message::Pong(s),

View File

@ -12,9 +12,9 @@ enum ResourceType {
impl fmt::Display for ResourceType { impl fmt::Display for ResourceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match *self {
&ResourceType::Async => write!(f, "to_async"), ResourceType::Async => write!(f, "to_async"),
&ResourceType::Sync => write!(f, "to"), ResourceType::Sync => write!(f, "to"),
} }
} }
} }
@ -34,16 +34,16 @@ pub enum GuardType {
impl fmt::Display for GuardType { impl fmt::Display for GuardType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match *self {
&GuardType::Get => write!(f, "Get"), GuardType::Get => write!(f, "Get"),
&GuardType::Post => write!(f, "Post"), GuardType::Post => write!(f, "Post"),
&GuardType::Put => write!(f, "Put"), GuardType::Put => write!(f, "Put"),
&GuardType::Delete => write!(f, "Delete"), GuardType::Delete => write!(f, "Delete"),
&GuardType::Head => write!(f, "Head"), GuardType::Head => write!(f, "Head"),
&GuardType::Connect => write!(f, "Connect"), GuardType::Connect => write!(f, "Connect"),
&GuardType::Options => write!(f, "Options"), GuardType::Options => write!(f, "Options"),
&GuardType::Trace => write!(f, "Trace"), GuardType::Trace => write!(f, "Trace"),
&GuardType::Patch => write!(f, "Patch"), GuardType::Patch => write!(f, "Patch"),
} }
} }
} }
@ -92,37 +92,27 @@ impl actix_web::dev::HttpServiceFactory for {name} {{
fn guess_resource_type(typ: &syn::Type) -> ResourceType { fn guess_resource_type(typ: &syn::Type) -> ResourceType {
let mut guess = ResourceType::Sync; let mut guess = ResourceType::Sync;
match typ { if let syn::Type::ImplTrait(typ) = typ {
syn::Type::ImplTrait(typ) => { for bound in typ.bounds.iter() {
for bound in typ.bounds.iter() { if let syn::TypeParamBound::Trait(bound) = bound {
match bound { for bound in bound.path.segments.iter() {
syn::TypeParamBound::Trait(bound) => { if bound.ident == "Future" {
for bound in bound.path.segments.iter() { guess = ResourceType::Async;
if bound.ident == "Future" { break;
guess = ResourceType::Async; } else if bound.ident == "Responder" {
break; guess = ResourceType::Sync;
} else if bound.ident == "Responder" { break;
guess = ResourceType::Sync;
break;
}
}
} }
_ => (),
} }
} }
} }
_ => (),
} }
guess guess
} }
impl Args { impl Args {
pub fn new( pub fn new(args: &[syn::NestedMeta], input: TokenStream, guard: GuardType) -> Self {
args: &Vec<syn::NestedMeta>,
input: TokenStream,
guard: GuardType,
) -> Self {
if args.is_empty() { if args.is_empty() {
panic!( panic!(
"invalid server definition, expected: #[{}(\"some path\")]", "invalid server definition, expected: #[{}(\"some path\")]",
@ -164,9 +154,10 @@ impl Args {
ResourceType::Async ResourceType::Async
} else { } else {
match ast.decl.output { match ast.decl.output {
syn::ReturnType::Default => { syn::ReturnType::Default => panic!(
panic!("Function {} has no return type. Cannot be used as handler") "Function {} has no return type. Cannot be used as handler",
} name
),
syn::ReturnType::Type(_, ref typ) => guess_resource_type(typ.as_ref()), syn::ReturnType::Type(_, ref typ) => guess_resource_type(typ.as_ref()),
} }
}; };

View File

@ -21,6 +21,12 @@ pub struct ClientBuilder {
max_redirects: usize, max_redirects: usize,
} }
impl Default for ClientBuilder {
fn default() -> Self {
Self::new()
}
}
impl ClientBuilder { impl ClientBuilder {
pub fn new() -> Self { pub fn new() -> Self {
ClientBuilder { ClientBuilder {

View File

@ -20,7 +20,7 @@ pub(crate) trait Connect {
head: RequestHead, head: RequestHead,
body: Body, body: Body,
addr: Option<net::SocketAddr>, addr: Option<net::SocketAddr>,
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>>; ) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>>;
/// Send request, returns Response and Framed /// Send request, returns Response and Framed
fn open_tunnel( fn open_tunnel(
@ -28,7 +28,7 @@ pub(crate) trait Connect {
head: RequestHead, head: RequestHead,
addr: Option<net::SocketAddr>, addr: Option<net::SocketAddr>,
) -> Box< ) -> Box<
Future< dyn Future<
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>), Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
Error = SendRequestError, Error = SendRequestError,
>, >,
@ -49,7 +49,7 @@ where
head: RequestHead, head: RequestHead,
body: Body, body: Body,
addr: Option<net::SocketAddr>, addr: Option<net::SocketAddr>,
) -> Box<Future<Item = ClientResponse, Error = SendRequestError>> { ) -> Box<dyn Future<Item = ClientResponse, Error = SendRequestError>> {
Box::new( Box::new(
self.0 self.0
// connect to the host // connect to the host
@ -69,7 +69,7 @@ where
head: RequestHead, head: RequestHead,
addr: Option<net::SocketAddr>, addr: Option<net::SocketAddr>,
) -> Box< ) -> Box<
Future< dyn Future<
Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>), Item = (ResponseHead, Framed<BoxedSocket, ClientCodec>),
Error = SendRequestError, Error = SendRequestError,
>, >,
@ -93,21 +93,21 @@ where
} }
trait AsyncSocket { trait AsyncSocket {
fn as_read(&self) -> &AsyncRead; fn as_read(&self) -> &dyn AsyncRead;
fn as_read_mut(&mut self) -> &mut AsyncRead; fn as_read_mut(&mut self) -> &mut dyn AsyncRead;
fn as_write(&mut self) -> &mut AsyncWrite; fn as_write(&mut self) -> &mut dyn AsyncWrite;
} }
struct Socket<T: AsyncRead + AsyncWrite>(T); struct Socket<T: AsyncRead + AsyncWrite>(T);
impl<T: AsyncRead + AsyncWrite> AsyncSocket for Socket<T> { impl<T: AsyncRead + AsyncWrite> AsyncSocket for Socket<T> {
fn as_read(&self) -> &AsyncRead { fn as_read(&self) -> &dyn AsyncRead {
&self.0 &self.0
} }
fn as_read_mut(&mut self) -> &mut AsyncRead { fn as_read_mut(&mut self) -> &mut dyn AsyncRead {
&mut self.0 &mut self.0
} }
fn as_write(&mut self) -> &mut AsyncWrite { fn as_write(&mut self) -> &mut dyn AsyncWrite {
&mut self.0 &mut self.0
} }
} }

View File

@ -1,3 +1,4 @@
#![allow(clippy::borrow_interior_mutable_const)]
//! An HTTP Client //! An HTTP Client
//! //!
//! ```rust //! ```rust

View File

@ -185,9 +185,7 @@ impl ClientRequest {
{ {
match HeaderName::try_from(key) { match HeaderName::try_from(key) {
Ok(key) => match value.try_into() { Ok(key) => match value.try_into() {
Ok(value) => { Ok(value) => self.head.headers.append(key, value),
let _ = self.head.headers.append(key, value);
}
Err(e) => self.err = Some(e.into()), Err(e) => self.err = Some(e.into()),
}, },
Err(e) => self.err = Some(e.into()), Err(e) => self.err = Some(e.into()),
@ -203,9 +201,7 @@ impl ClientRequest {
{ {
match HeaderName::try_from(key) { match HeaderName::try_from(key) {
Ok(key) => match value.try_into() { Ok(key) => match value.try_into() {
Ok(value) => { Ok(value) => self.head.headers.insert(key, value),
let _ = self.head.headers.insert(key, value);
}
Err(e) => self.err = Some(e.into()), Err(e) => self.err = Some(e.into()),
}, },
Err(e) => self.err = Some(e.into()), Err(e) => self.err = Some(e.into()),
@ -223,9 +219,7 @@ impl ClientRequest {
Ok(key) => { Ok(key) => {
if !self.head.headers.contains_key(&key) { if !self.head.headers.contains_key(&key) {
match value.try_into() { match value.try_into() {
Ok(value) => { Ok(value) => self.head.headers.insert(key, value),
let _ = self.head.headers.insert(key, value);
}
Err(e) => self.err = Some(e.into()), Err(e) => self.err = Some(e.into()),
} }
} }
@ -257,9 +251,7 @@ impl ClientRequest {
HeaderValue: HttpTryFrom<V>, HeaderValue: HttpTryFrom<V>,
{ {
match HeaderValue::try_from(value) { match HeaderValue::try_from(value) {
Ok(value) => { Ok(value) => self.head.headers.insert(header::CONTENT_TYPE, value),
let _ = self.head.headers.insert(header::CONTENT_TYPE, value);
}
Err(e) => self.err = Some(e.into()), Err(e) => self.err = Some(e.into()),
} }
self self
@ -321,7 +313,7 @@ impl ClientRequest {
/// })); /// }));
/// } /// }
/// ``` /// ```
pub fn cookie<'c>(mut self, cookie: Cookie<'c>) -> Self { pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
if self.cookies.is_none() { if self.cookies.is_none() {
let mut jar = CookieJar::new(); let mut jar = CookieJar::new();
jar.add(cookie.into_owned()); jar.add(cookie.into_owned());
@ -465,7 +457,7 @@ impl ClientRequest {
}); });
// set request timeout // set request timeout
if let Some(timeout) = slf.timeout.or_else(|| config.timeout.clone()) { if let Some(timeout) = slf.timeout.or_else(|| config.timeout) {
Either::B(Either::A(Timeout::new(fut, timeout).map_err(|e| { Either::B(Either::A(Timeout::new(fut, timeout).map_err(|e| {
if let Some(e) = e.into_inner() { if let Some(e) = e.into_inner() {
e e

View File

@ -68,7 +68,7 @@ impl TestResponse {
} }
/// Set cookie for this response /// Set cookie for this response
pub fn cookie<'a>(mut self, cookie: Cookie<'a>) -> Self { pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
self.cookies.add(cookie.into_owned()); self.cookies.add(cookie.into_owned());
self self
} }

View File

@ -90,7 +90,7 @@ impl WebsocketsRequest {
} }
/// Set a cookie /// Set a cookie
pub fn cookie<'c>(mut self, cookie: Cookie<'c>) -> Self { pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
if self.cookies.is_none() { if self.cookies.is_none() {
let mut jar = CookieJar::new(); let mut jar = CookieJar::new();
jar.add(cookie.into_owned()); jar.add(cookie.into_owned());

View File

@ -23,16 +23,17 @@ use crate::service::{
}; };
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type FnDataFactory = Box<Fn() -> Box<dyn Future<Item = Box<DataFactory>, Error = ()>>>; type FnDataFactory =
Box<dyn Fn() -> Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>;
/// Application builder - structure that follows the builder pattern /// Application builder - structure that follows the builder pattern
/// for building application instances. /// for building application instances.
pub struct App<T, B> { pub struct App<T, B> {
endpoint: T, endpoint: T,
services: Vec<Box<ServiceFactory>>, services: Vec<Box<dyn ServiceFactory>>,
default: Option<Rc<HttpNewService>>, default: Option<Rc<HttpNewService>>,
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>, factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
data: Vec<Box<DataFactory>>, data: Vec<Box<dyn DataFactory>>,
data_factories: Vec<FnDataFactory>, data_factories: Vec<FnDataFactory>,
config: AppConfigInner, config: AppConfigInner,
external: Vec<ResourceDef>, external: Vec<ResourceDef>,

View File

@ -18,14 +18,15 @@ use crate::request::{HttpRequest, HttpRequestPool};
use crate::rmap::ResourceMap; use crate::rmap::ResourceMap;
use crate::service::{ServiceFactory, ServiceRequest, ServiceResponse}; use crate::service::{ServiceFactory, ServiceRequest, ServiceResponse};
type Guards = Vec<Box<Guard>>; type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = Either< type BoxedResponse = Either<
FutureResult<ServiceResponse, Error>, FutureResult<ServiceResponse, Error>,
Box<Future<Item = ServiceResponse, Error = Error>>, Box<dyn Future<Item = ServiceResponse, Error = Error>>,
>; >;
type FnDataFactory = Box<Fn() -> Box<dyn Future<Item = Box<DataFactory>, Error = ()>>>; type FnDataFactory =
Box<dyn Fn() -> Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>;
/// Service factory to convert `Request` to a `ServiceRequest<S>`. /// Service factory to convert `Request` to a `ServiceRequest<S>`.
/// It also executes data factories. /// It also executes data factories.
@ -40,10 +41,10 @@ where
>, >,
{ {
pub(crate) endpoint: T, pub(crate) endpoint: T,
pub(crate) data: Rc<Vec<Box<DataFactory>>>, pub(crate) data: Rc<Vec<Box<dyn DataFactory>>>,
pub(crate) data_factories: Rc<Vec<FnDataFactory>>, pub(crate) data_factories: Rc<Vec<FnDataFactory>>,
pub(crate) config: RefCell<AppConfig>, pub(crate) config: RefCell<AppConfig>,
pub(crate) services: Rc<RefCell<Vec<Box<ServiceFactory>>>>, pub(crate) services: Rc<RefCell<Vec<Box<dyn ServiceFactory>>>>,
pub(crate) default: Option<Rc<HttpNewService>>, pub(crate) default: Option<Rc<HttpNewService>>,
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>, pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
pub(crate) external: RefCell<Vec<ResourceDef>>, pub(crate) external: RefCell<Vec<ResourceDef>>,
@ -142,9 +143,9 @@ where
endpoint_fut: T::Future, endpoint_fut: T::Future,
rmap: Rc<ResourceMap>, rmap: Rc<ResourceMap>,
config: AppConfig, config: AppConfig,
data: Rc<Vec<Box<DataFactory>>>, data: Rc<Vec<Box<dyn DataFactory>>>,
data_factories: Vec<Box<DataFactory>>, data_factories: Vec<Box<dyn DataFactory>>,
data_factories_fut: Vec<Box<dyn Future<Item = Box<DataFactory>, Error = ()>>>, data_factories_fut: Vec<Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>,
_t: PhantomData<B>, _t: PhantomData<B>,
} }
@ -297,14 +298,14 @@ impl NewService for AppRoutingFactory {
} }
} }
type HttpServiceFut = Box<Future<Item = HttpService, Error = ()>>; type HttpServiceFut = Box<dyn Future<Item = HttpService, Error = ()>>;
/// Create app service /// Create app service
#[doc(hidden)] #[doc(hidden)]
pub struct AppRoutingFactoryResponse { pub struct AppRoutingFactoryResponse {
fut: Vec<CreateAppRoutingItem>, fut: Vec<CreateAppRoutingItem>,
default: Option<HttpService>, default: Option<HttpService>,
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>, default_fut: Option<Box<dyn Future<Item = HttpService, Error = ()>>>,
} }
enum CreateAppRoutingItem { enum CreateAppRoutingItem {

View File

@ -16,7 +16,7 @@ use crate::service::{
ServiceResponse, ServiceResponse,
}; };
type Guards = Vec<Box<Guard>>; type Guards = Vec<Box<dyn Guard>>;
type HttpNewService = type HttpNewService =
boxed::BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; boxed::BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
@ -31,7 +31,7 @@ pub struct AppService {
Option<Guards>, Option<Guards>,
Option<Rc<ResourceMap>>, Option<Rc<ResourceMap>>,
)>, )>,
service_data: Rc<Vec<Box<DataFactory>>>, service_data: Rc<Vec<Box<dyn DataFactory>>>,
} }
impl AppService { impl AppService {
@ -39,7 +39,7 @@ impl AppService {
pub(crate) fn new( pub(crate) fn new(
config: AppConfig, config: AppConfig,
default: Rc<HttpNewService>, default: Rc<HttpNewService>,
service_data: Rc<Vec<Box<DataFactory>>>, service_data: Rc<Vec<Box<dyn DataFactory>>>,
) -> Self { ) -> Self {
AppService { AppService {
config, config,
@ -101,7 +101,7 @@ impl AppService {
pub fn register_service<F, S>( pub fn register_service<F, S>(
&mut self, &mut self,
rdef: ResourceDef, rdef: ResourceDef,
guards: Option<Vec<Box<Guard>>>, guards: Option<Vec<Box<dyn Guard>>>,
service: F, service: F,
nested: Option<Rc<ResourceMap>>, nested: Option<Rc<ResourceMap>>,
) where ) where
@ -174,8 +174,8 @@ impl Default for AppConfigInner {
/// to set of external methods. This could help with /// to set of external methods. This could help with
/// modularization of big application configuration. /// modularization of big application configuration.
pub struct ServiceConfig { pub struct ServiceConfig {
pub(crate) services: Vec<Box<ServiceFactory>>, pub(crate) services: Vec<Box<dyn ServiceFactory>>,
pub(crate) data: Vec<Box<DataFactory>>, pub(crate) data: Vec<Box<dyn DataFactory>>,
pub(crate) external: Vec<ResourceDef>, pub(crate) external: Vec<ResourceDef>,
} }

View File

@ -118,7 +118,7 @@ impl<T: 'static> FromRequest for Data<T> {
impl<T: 'static> DataFactory for Data<T> { impl<T: 'static> DataFactory for Data<T> {
fn create(&self, extensions: &mut Extensions) -> bool { fn create(&self, extensions: &mut Extensions) -> bool {
if !extensions.contains::<Data<T>>() { if !extensions.contains::<Data<T>>() {
let _ = extensions.insert(Data(self.0.clone())); extensions.insert(Data(self.0.clone()));
true true
} else { } else {
false false

View File

@ -94,7 +94,7 @@ where
{ {
type Config = T::Config; type Config = T::Config;
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Option<T>, Error = Error>>; type Future = Box<dyn Future<Item = Option<T>, Error = Error>>;
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
@ -165,7 +165,7 @@ where
{ {
type Config = T::Config; type Config = T::Config;
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Result<T, T::Error>, Error = Error>>; type Future = Box<dyn Future<Item = Result<T, T::Error>, Error = Error>>;
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {

View File

@ -100,7 +100,7 @@ pub fn Any<F: Guard + 'static>(guard: F) -> AnyGuard {
} }
/// Matches if any of supplied guards matche. /// Matches if any of supplied guards matche.
pub struct AnyGuard(Vec<Box<Guard>>); pub struct AnyGuard(Vec<Box<dyn Guard>>);
impl AnyGuard { impl AnyGuard {
/// Add guard to a list of guards to check /// Add guard to a list of guards to check
@ -140,7 +140,7 @@ pub fn All<F: Guard + 'static>(guard: F) -> AllGuard {
} }
/// Matches if all of supplied guards. /// Matches if all of supplied guards.
pub struct AllGuard(Vec<Box<Guard>>); pub struct AllGuard(Vec<Box<dyn Guard>>);
impl AllGuard { impl AllGuard {
/// Add new guard to the list of guards to check /// Add new guard to the list of guards to check
@ -167,7 +167,7 @@ pub fn Not<F: Guard + 'static>(guard: F) -> NotGuard {
} }
#[doc(hidden)] #[doc(hidden)]
pub struct NotGuard(Box<Guard>); pub struct NotGuard(Box<dyn Guard>);
impl Guard for NotGuard { impl Guard for NotGuard {
fn check(&self, request: &RequestHead) -> bool { fn check(&self, request: &RequestHead) -> bool {

View File

@ -250,7 +250,7 @@ where
Ok(Async::Ready(res)) => { Ok(Async::Ready(res)) => {
self.fut2 = self.fut2 =
Some(res.respond_to(self.req.as_ref().unwrap()).into_future()); Some(res.respond_to(self.req.as_ref().unwrap()).into_future());
return self.poll(); self.poll()
} }
Ok(Async::NotReady) => Ok(Async::NotReady), Ok(Async::NotReady) => Ok(Async::NotReady),
Err(e) => { Err(e) => {

View File

@ -25,7 +25,7 @@ impl ConnectionInfo {
Ref::map(req.extensions(), |e| e.get().unwrap()) Ref::map(req.extensions(), |e| e.get().unwrap())
} }
#[allow(clippy::cyclomatic_complexity)] #[allow(clippy::cognitive_complexity)]
fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo { fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo {
let mut host = None; let mut host = None;
let mut scheme = None; let mut scheme = None;

View File

@ -1,3 +1,4 @@
#![allow(clippy::borrow_interior_mutable_const)]
//! Actix web is a small, pragmatic, and extremely fast web framework //! Actix web is a small, pragmatic, and extremely fast web framework
//! for Rust. //! for Rust.
//! //!
@ -134,6 +135,8 @@ pub mod dev {
//! ``` //! ```
pub use crate::config::{AppConfig, AppService}; pub use crate::config::{AppConfig, AppService};
#[doc(hidden)]
pub use crate::handler::{AsyncFactory, Factory};
pub use crate::info::ConnectionInfo; pub use crate::info::ConnectionInfo;
pub use crate::rmap::ResourceMap; pub use crate::rmap::ResourceMap;
pub use crate::service::{ pub use crate::service::{

View File

@ -119,7 +119,7 @@ where
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready() self.service.poll_ready()

View File

@ -15,10 +15,10 @@ pub enum ErrorHandlerResponse<B> {
/// New http response got generated /// New http response got generated
Response(ServiceResponse<B>), Response(ServiceResponse<B>),
/// Result is a future that resolves to a new http response /// Result is a future that resolves to a new http response
Future(Box<Future<Item = ServiceResponse<B>, Error = Error>>), Future(Box<dyn Future<Item = ServiceResponse<B>, Error = Error>>),
} }
type ErrorHandler<B> = Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>; type ErrorHandler<B> = dyn Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>;
/// `Middleware` for allowing custom handlers for responses. /// `Middleware` for allowing custom handlers for responses.
/// ///
@ -117,7 +117,7 @@ where
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready() self.service.poll_ready()

View File

@ -415,9 +415,9 @@ impl FormatText {
)) ))
}; };
} }
FormatText::UrlPath => *self = FormatText::Str(format!("{}", req.path())), FormatText::UrlPath => *self = FormatText::Str(req.path().to_string()),
FormatText::RequestTime => { FormatText::RequestTime => {
*self = FormatText::Str(format!("{}", now.rfc3339())) *self = FormatText::Str(now.rfc3339().to_string())
} }
FormatText::RequestHeader(ref name) => { FormatText::RequestHeader(ref name) => {
let s = if let Some(val) = req.headers().get(name) { let s = if let Some(val) = req.headers().get(name) {
@ -444,7 +444,9 @@ impl FormatText {
} }
} }
pub(crate) struct FormatDisplay<'a>(&'a Fn(&mut Formatter) -> Result<(), fmt::Error>); pub(crate) struct FormatDisplay<'a>(
&'a dyn Fn(&mut Formatter) -> Result<(), fmt::Error>,
);
impl<'a> fmt::Display for FormatDisplay<'a> { impl<'a> fmt::Display for FormatDisplay<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> { fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {

View File

@ -174,6 +174,12 @@ impl HttpRequest {
self.url_for(name, &NO_PARAMS) self.url_for(name, &NO_PARAMS)
} }
#[inline]
/// Get a reference to a `ResourceMap` of current application.
pub fn resource_map(&self) -> &ResourceMap {
&self.0.rmap
}
/// Peer socket address /// Peer socket address
/// ///
/// Peer address is actual socket address, if proxy is used in front of /// Peer address is actual socket address, if proxy is used in front of

View File

@ -50,7 +50,7 @@ pub struct Resource<T = ResourceEndpoint> {
name: Option<String>, name: Option<String>,
routes: Vec<Route>, routes: Vec<Route>,
data: Option<Extensions>, data: Option<Extensions>,
guards: Vec<Box<Guard>>, guards: Vec<Box<dyn Guard>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>, default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
factory_ref: Rc<RefCell<Option<ResourceFactory>>>, factory_ref: Rc<RefCell<Option<ResourceFactory>>>,
} }
@ -118,7 +118,7 @@ where
self self
} }
pub(crate) fn add_guards(mut self, guards: Vec<Box<Guard>>) -> Self { pub(crate) fn add_guards(mut self, guards: Vec<Box<dyn Guard>>) -> Self {
self.guards.extend(guards); self.guards.extend(guards);
self self
} }
@ -245,7 +245,7 @@ where
/// ```rust /// ```rust
/// # use actix_web::*; /// # use actix_web::*;
/// # use futures::future::Future; /// # use futures::future::Future;
/// # fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> { /// # fn index(req: HttpRequest) -> Box<dyn Future<Item=HttpResponse, Error=Error>> {
/// # unimplemented!() /// # unimplemented!()
/// # } /// # }
/// App::new().service(web::resource("/").route(web::route().to_async(index))); /// App::new().service(web::resource("/").route(web::route().to_async(index)));
@ -426,7 +426,7 @@ where
fn into_new_service(self) -> T { fn into_new_service(self) -> T {
*self.factory_ref.borrow_mut() = Some(ResourceFactory { *self.factory_ref.borrow_mut() = Some(ResourceFactory {
routes: self.routes, routes: self.routes,
data: self.data.map(|data| Rc::new(data)), data: self.data.map(Rc::new),
default: self.default, default: self.default,
}); });
@ -478,7 +478,7 @@ pub struct CreateResourceService {
fut: Vec<CreateRouteServiceItem>, fut: Vec<CreateRouteServiceItem>,
data: Option<Rc<Extensions>>, data: Option<Rc<Extensions>>,
default: Option<HttpService>, default: Option<HttpService>,
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>, default_fut: Option<Box<dyn Future<Item = HttpService, Error = ()>>>,
} }
impl Future for CreateResourceService { impl Future for CreateResourceService {
@ -542,7 +542,7 @@ impl Service for ResourceService {
type Error = Error; type Error = Error;
type Future = Either< type Future = Either<
FutureResult<ServiceResponse, Error>, FutureResult<ServiceResponse, Error>,
Box<Future<Item = ServiceResponse, Error = Error>>, Box<dyn Future<Item = ServiceResponse, Error = Error>>,
>; >;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {

View File

@ -337,7 +337,7 @@ impl<T: Responder> Future for CustomResponderFut<T> {
/// use actix_web::{Either, Error, HttpResponse}; /// use actix_web::{Either, Error, HttpResponse};
/// ///
/// type RegisterResult = /// type RegisterResult =
/// Either<HttpResponse, Box<Future<Item = HttpResponse, Error = Error>>>; /// Either<HttpResponse, Box<dyn Future<Item = HttpResponse, Error = Error>>>;
/// ///
/// fn index() -> RegisterResult { /// fn index() -> RegisterResult {
/// if is_a_variant() { /// if is_a_variant() {
@ -411,13 +411,13 @@ where
} }
} }
impl<I, E> Responder for Box<Future<Item = I, Error = E>> impl<I, E> Responder for Box<dyn Future<Item = I, Error = E>>
where where
I: Responder + 'static, I: Responder + 'static,
E: Into<Error> + 'static, E: Into<Error> + 'static,
{ {
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Response, Error = Error>>; type Future = Box<dyn Future<Item = Response, Error = Error>>;
#[inline] #[inline]
fn respond_to(self, req: &HttpRequest) -> Self::Future { fn respond_to(self, req: &HttpRequest) -> Self::Future {

View File

@ -123,7 +123,7 @@ impl ResourceMap {
I: AsRef<str>, I: AsRef<str>,
{ {
if let Some(pattern) = self.named.get(name) { if let Some(pattern) = self.named.get(name) {
if pattern.pattern().starts_with("/") { if pattern.pattern().starts_with('/') {
self.fill_root(path, elements)?; self.fill_root(path, elements)?;
} }
if pattern.resource_path(path, elements) { if pattern.resource_path(path, elements) {

View File

@ -13,26 +13,26 @@ use crate::service::{ServiceRequest, ServiceResponse};
use crate::HttpResponse; use crate::HttpResponse;
type BoxedRouteService<Req, Res> = Box< type BoxedRouteService<Req, Res> = Box<
Service< dyn Service<
Request = Req, Request = Req,
Response = Res, Response = Res,
Error = Error, Error = Error,
Future = Either< Future = Either<
FutureResult<Res, Error>, FutureResult<Res, Error>,
Box<Future<Item = Res, Error = Error>>, Box<dyn Future<Item = Res, Error = Error>>,
>, >,
>, >,
>; >;
type BoxedRouteNewService<Req, Res> = Box< type BoxedRouteNewService<Req, Res> = Box<
NewService< dyn NewService<
Config = (), Config = (),
Request = Req, Request = Req,
Response = Res, Response = Res,
Error = Error, Error = Error,
InitError = (), InitError = (),
Service = BoxedRouteService<Req, Res>, Service = BoxedRouteService<Req, Res>,
Future = Box<Future<Item = BoxedRouteService<Req, Res>, Error = ()>>, Future = Box<dyn Future<Item = BoxedRouteService<Req, Res>, Error = ()>>,
>, >,
>; >;
@ -42,7 +42,7 @@ type BoxedRouteNewService<Req, Res> = Box<
/// If handler is not explicitly set, default *404 Not Found* handler is used. /// If handler is not explicitly set, default *404 Not Found* handler is used.
pub struct Route { pub struct Route {
service: BoxedRouteNewService<ServiceRequest, ServiceResponse>, service: BoxedRouteNewService<ServiceRequest, ServiceResponse>,
guards: Rc<Vec<Box<Guard>>>, guards: Rc<Vec<Box<dyn Guard>>>,
} }
impl Route { impl Route {
@ -56,7 +56,7 @@ impl Route {
} }
} }
pub(crate) fn take_guards(&mut self) -> Vec<Box<Guard>> { pub(crate) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> {
std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new()) std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new())
} }
} }
@ -78,12 +78,13 @@ impl NewService for Route {
} }
} }
type RouteFuture = type RouteFuture = Box<
Box<Future<Item = BoxedRouteService<ServiceRequest, ServiceResponse>, Error = ()>>; dyn Future<Item = BoxedRouteService<ServiceRequest, ServiceResponse>, Error = ()>,
>;
pub struct CreateRouteService { pub struct CreateRouteService {
fut: RouteFuture, fut: RouteFuture,
guards: Rc<Vec<Box<Guard>>>, guards: Rc<Vec<Box<dyn Guard>>>,
} }
impl Future for CreateRouteService { impl Future for CreateRouteService {
@ -103,7 +104,7 @@ impl Future for CreateRouteService {
pub struct RouteService { pub struct RouteService {
service: BoxedRouteService<ServiceRequest, ServiceResponse>, service: BoxedRouteService<ServiceRequest, ServiceResponse>,
guards: Rc<Vec<Box<Guard>>>, guards: Rc<Vec<Box<dyn Guard>>>,
} }
impl RouteService { impl RouteService {
@ -123,7 +124,7 @@ impl Service for RouteService {
type Error = Error; type Error = Error;
type Future = Either< type Future = Either<
FutureResult<Self::Response, Self::Error>, FutureResult<Self::Response, Self::Error>,
Box<Future<Item = Self::Response, Error = Self::Error>>, Box<dyn Future<Item = Self::Response, Error = Self::Error>>,
>; >;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
@ -317,7 +318,7 @@ where
type Error = Error; type Error = Error;
type InitError = (); type InitError = ();
type Service = BoxedRouteService<ServiceRequest, Self::Response>; type Service = BoxedRouteService<ServiceRequest, Self::Response>;
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>; type Future = Box<dyn Future<Item = Self::Service, Error = Self::InitError>>;
fn new_service(&self, _: &()) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
Box::new( Box::new(
@ -351,7 +352,7 @@ where
type Error = Error; type Error = Error;
type Future = Either< type Future = Either<
FutureResult<Self::Response, Self::Error>, FutureResult<Self::Response, Self::Error>,
Box<Future<Item = Self::Response, Error = Self::Error>>, Box<dyn Future<Item = Self::Response, Error = Self::Error>>,
>; >;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {

View File

@ -23,12 +23,12 @@ use crate::service::{
ServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse, ServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse,
}; };
type Guards = Vec<Box<Guard>>; type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>; type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>; type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = Either< type BoxedResponse = Either<
FutureResult<ServiceResponse, Error>, FutureResult<ServiceResponse, Error>,
Box<Future<Item = ServiceResponse, Error = Error>>, Box<dyn Future<Item = ServiceResponse, Error = Error>>,
>; >;
/// Resources scope. /// Resources scope.
@ -64,8 +64,8 @@ pub struct Scope<T = ScopeEndpoint> {
endpoint: T, endpoint: T,
rdef: String, rdef: String,
data: Option<Extensions>, data: Option<Extensions>,
services: Vec<Box<ServiceFactory>>, services: Vec<Box<dyn ServiceFactory>>,
guards: Vec<Box<Guard>>, guards: Vec<Box<dyn Guard>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>, default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
external: Vec<ResourceDef>, external: Vec<ResourceDef>,
factory_ref: Rc<RefCell<Option<ScopeFactory>>>, factory_ref: Rc<RefCell<Option<ScopeFactory>>>,
@ -195,7 +195,7 @@ where
self.external.extend(cfg.external); self.external.extend(cfg.external);
if !cfg.data.is_empty() { if !cfg.data.is_empty() {
let mut data = self.data.unwrap_or_else(|| Extensions::new()); let mut data = self.data.unwrap_or_else(Extensions::new);
for value in cfg.data.iter() { for value in cfg.data.iter() {
value.create(&mut data); value.create(&mut data);
@ -425,7 +425,7 @@ where
// complete scope pipeline creation // complete scope pipeline creation
*self.factory_ref.borrow_mut() = Some(ScopeFactory { *self.factory_ref.borrow_mut() = Some(ScopeFactory {
data: self.data.take().map(|data| Rc::new(data)), data: self.data.take().map(Rc::new),
default: self.default.clone(), default: self.default.clone(),
services: Rc::new( services: Rc::new(
cfg.into_services() cfg.into_services()
@ -503,10 +503,10 @@ pub struct ScopeFactoryResponse {
fut: Vec<CreateScopeServiceItem>, fut: Vec<CreateScopeServiceItem>,
data: Option<Rc<Extensions>>, data: Option<Rc<Extensions>>,
default: Option<HttpService>, default: Option<HttpService>,
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>, default_fut: Option<Box<dyn Future<Item = HttpService, Error = ()>>>,
} }
type HttpServiceFut = Box<Future<Item = HttpService, Error = ()>>; type HttpServiceFut = Box<dyn Future<Item = HttpService, Error = ()>>;
enum CreateScopeServiceItem { enum CreateScopeServiceItem {
Future(Option<ResourceDef>, Option<Guards>, HttpServiceFut), Future(Option<ResourceDef>, Option<Guards>, HttpServiceFut),
@ -578,7 +578,7 @@ impl Future for ScopeFactoryResponse {
pub struct ScopeService { pub struct ScopeService {
data: Option<Rc<Extensions>>, data: Option<Rc<Extensions>>,
router: Router<HttpService, Vec<Box<Guard>>>, router: Router<HttpService, Vec<Box<dyn Guard>>>,
default: Option<HttpService>, default: Option<HttpService>,
_ready: Option<(ServiceRequest, ResourceInfo)>, _ready: Option<(ServiceRequest, ResourceInfo)>,
} }

View File

@ -288,13 +288,13 @@ where
lst, lst,
move || { move || {
let c = cfg.lock(); let c = cfg.lock();
acceptor.clone().map_err(|e| SslError::Ssl(e)).and_then( acceptor.clone().map_err(SslError::Ssl).and_then(
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown) .client_disconnect(c.client_shutdown)
.finish(factory()) .finish(factory())
.map_err(|e| SslError::Service(e)) .map_err(SslError::Service)
.map_init_err(|_| ()), .map_init_err(|_| ()),
) )
}, },
@ -339,13 +339,13 @@ where
lst, lst,
move || { move || {
let c = cfg.lock(); let c = cfg.lock();
acceptor.clone().map_err(|e| SslError::Ssl(e)).and_then( acceptor.clone().map_err(SslError::Ssl).and_then(
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown) .client_disconnect(c.client_shutdown)
.finish(factory()) .finish(factory())
.map_err(|e| SslError::Service(e)) .map_err(SslError::Service)
.map_init_err(|_| ()), .map_init_err(|_| ()),
) )
}, },

View File

@ -18,6 +18,7 @@ use crate::dev::insert_slash;
use crate::guard::Guard; use crate::guard::Guard;
use crate::info::ConnectionInfo; use crate::info::ConnectionInfo;
use crate::request::HttpRequest; use crate::request::HttpRequest;
use crate::rmap::ResourceMap;
pub trait HttpServiceFactory { pub trait HttpServiceFactory {
fn register(self, config: &mut AppService); fn register(self, config: &mut AppService);
@ -169,10 +170,17 @@ impl ServiceRequest {
} }
#[inline] #[inline]
/// Get a mutable reference to the Path parameters.
pub fn match_info_mut(&mut self) -> &mut Path<Url> { pub fn match_info_mut(&mut self) -> &mut Path<Url> {
self.0.match_info_mut() self.0.match_info_mut()
} }
#[inline]
/// Get a reference to a `ResourceMap` of current application.
pub fn resource_map(&self) -> &ResourceMap {
self.0.resource_map()
}
/// Service configuration /// Service configuration
#[inline] #[inline]
pub fn app_config(&self) -> &AppConfig { pub fn app_config(&self) -> &AppConfig {
@ -399,7 +407,7 @@ impl<B: MessageBody> fmt::Debug for ServiceResponse<B> {
pub struct WebService { pub struct WebService {
rdef: String, rdef: String,
name: Option<String>, name: Option<String>,
guards: Vec<Box<Guard>>, guards: Vec<Box<dyn Guard>>,
} }
impl WebService { impl WebService {
@ -468,7 +476,7 @@ struct WebServiceImpl<T> {
srv: T, srv: T,
rdef: String, rdef: String,
name: Option<String>, name: Option<String>,
guards: Vec<Box<Guard>>, guards: Vec<Box<dyn Guard>>,
} }
impl<T> HttpServiceFactory for WebServiceImpl<T> impl<T> HttpServiceFactory for WebServiceImpl<T>

View File

@ -79,7 +79,7 @@ where
F: FnOnce() -> R, F: FnOnce() -> R,
R: IntoFuture, R: IntoFuture,
{ {
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f()))) RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(f)))
} }
#[doc(hidden)] #[doc(hidden)]

View File

@ -73,7 +73,7 @@ where
{ {
type Config = FormConfig; type Config = FormConfig;
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Self, Error = Error>>; type Future = Box<dyn Future<Item = Self, Error = Error>>;
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
@ -141,7 +141,7 @@ impl<T: fmt::Display> fmt::Display for Form<T> {
#[derive(Clone)] #[derive(Clone)]
pub struct FormConfig { pub struct FormConfig {
limit: usize, limit: usize,
ehandler: Option<Rc<Fn(UrlencodedError, &HttpRequest) -> Error>>, ehandler: Option<Rc<dyn Fn(UrlencodedError, &HttpRequest) -> Error>>,
} }
impl FormConfig { impl FormConfig {
@ -187,7 +187,7 @@ pub struct UrlEncoded<U> {
length: Option<usize>, length: Option<usize>,
encoding: &'static Encoding, encoding: &'static Encoding,
err: Option<UrlencodedError>, err: Option<UrlencodedError>,
fut: Option<Box<Future<Item = U, Error = UrlencodedError>>>, fut: Option<Box<dyn Future<Item = U, Error = UrlencodedError>>>,
} }
impl<U> UrlEncoded<U> { impl<U> UrlEncoded<U> {

View File

@ -169,7 +169,7 @@ where
T: DeserializeOwned + 'static, T: DeserializeOwned + 'static,
{ {
type Error = Error; type Error = Error;
type Future = Box<Future<Item = Self, Error = Error>>; type Future = Box<dyn Future<Item = Self, Error = Error>>;
type Config = JsonConfig; type Config = JsonConfig;
#[inline] #[inline]
@ -290,7 +290,7 @@ pub struct JsonBody<U> {
length: Option<usize>, length: Option<usize>,
stream: Option<Decompress<Payload>>, stream: Option<Decompress<Payload>>,
err: Option<JsonPayloadError>, err: Option<JsonPayloadError>,
fut: Option<Box<Future<Item = U, Error = JsonPayloadError>>>, fut: Option<Box<dyn Future<Item = U, Error = JsonPayloadError>>>,
} }
impl<U> JsonBody<U> impl<U> JsonBody<U>

View File

@ -224,7 +224,7 @@ where
/// ``` /// ```
#[derive(Clone)] #[derive(Clone)]
pub struct PathConfig { pub struct PathConfig {
ehandler: Option<Arc<Fn(PathError, &HttpRequest) -> Error + Send + Sync>>, ehandler: Option<Arc<dyn Fn(PathError, &HttpRequest) -> Error + Send + Sync>>,
} }
impl PathConfig { impl PathConfig {

View File

@ -124,11 +124,11 @@ impl FromRequest for Bytes {
type Config = PayloadConfig; type Config = PayloadConfig;
type Error = Error; type Error = Error;
type Future = type Future =
Either<Box<Future<Item = Bytes, Error = Error>>, FutureResult<Bytes, Error>>; Either<Box<dyn Future<Item = Bytes, Error = Error>>, FutureResult<Bytes, Error>>;
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
let mut tmp; let tmp;
let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() { let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() {
cfg cfg
} else { } else {
@ -177,12 +177,14 @@ impl FromRequest for Bytes {
impl FromRequest for String { impl FromRequest for String {
type Config = PayloadConfig; type Config = PayloadConfig;
type Error = Error; type Error = Error;
type Future = type Future = Either<
Either<Box<Future<Item = String, Error = Error>>, FutureResult<String, Error>>; Box<dyn Future<Item = String, Error = Error>>,
FutureResult<String, Error>,
>;
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
let mut tmp; let tmp;
let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() { let cfg = if let Some(cfg) = req.app_data::<PayloadConfig>() {
cfg cfg
} else { } else {
@ -291,7 +293,7 @@ pub struct HttpMessageBody {
length: Option<usize>, length: Option<usize>,
stream: Option<dev::Decompress<dev::Payload>>, stream: Option<dev::Decompress<dev::Payload>>,
err: Option<PayloadError>, err: Option<PayloadError>,
fut: Option<Box<Future<Item = Bytes, Error = PayloadError>>>, fut: Option<Box<dyn Future<Item = Bytes, Error = PayloadError>>>,
} }
impl HttpMessageBody { impl HttpMessageBody {

View File

@ -192,7 +192,8 @@ where
/// ``` /// ```
#[derive(Clone)] #[derive(Clone)]
pub struct QueryConfig { pub struct QueryConfig {
ehandler: Option<Arc<Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync>>, ehandler:
Option<Arc<dyn Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync>>,
} }
impl QueryConfig { impl QueryConfig {

View File

@ -65,7 +65,7 @@ where
F: FnOnce() -> R, F: FnOnce() -> R,
R: IntoFuture, R: IntoFuture,
{ {
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f()))) RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(f)))
} }
/// The `TestServer` type. /// The `TestServer` type.
@ -107,6 +107,7 @@ pub struct TestServerRuntime {
} }
impl TestServer { impl TestServer {
#[allow(clippy::new_ret_no_self)]
/// Start new test server with application factory /// Start new test server with application factory
pub fn new<F: StreamServiceFactory>(factory: F) -> TestServerRuntime { pub fn new<F: StreamServiceFactory>(factory: F) -> TestServerRuntime {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
@ -191,7 +192,7 @@ impl TestServerRuntime {
F: FnOnce() -> R, F: FnOnce() -> R,
R: Future, R: Future,
{ {
self.rt.block_on(lazy(|| f())) self.rt.block_on(lazy(f))
} }
/// Execute function on current core /// Execute function on current core