mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-12 13:33:41 +02:00
Compare commits
10 Commits
http-v0.2.
...
web-v1.0.5
Author | SHA1 | Date | |
---|---|---|---|
6b7df6b242 | |||
b6ff786ed3 | |||
9c3789cbd0 | |||
29098f8397 | |||
fbdda8acb1 | |||
d03296237e | |||
b36fdc46db | |||
2a2d7f5768 | |||
4092c7f326 | |||
ef3e1037a8 |
14
CHANGES.md
14
CHANGES.md
@ -1,5 +1,19 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [1.0.5] - 2019-07-18
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Unix domain sockets (HttpServer::bind_uds) #92
|
||||||
|
|
||||||
|
* Actix now logs errors resulting in "internal server error" responses always, with the `error`
|
||||||
|
logging level
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Restored logging of errors through the `Logger` middleware
|
||||||
|
|
||||||
|
|
||||||
## [1.0.4] - 2019-07-17
|
## [1.0.4] - 2019-07-17
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
19
Cargo.toml
19
Cargo.toml
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-web"
|
name = "actix-web"
|
||||||
version = "1.0.4"
|
version = "1.0.5"
|
||||||
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"
|
||||||
@ -16,7 +16,7 @@ exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
|||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls"]
|
features = ["ssl", "brotli", "flate2-zlib", "secure-cookies", "client", "rust-tls", "uds"]
|
||||||
|
|
||||||
[badges]
|
[badges]
|
||||||
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
travis-ci = { repository = "actix/actix-web", branch = "master" }
|
||||||
@ -68,6 +68,9 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
|||||||
# rustls
|
# rustls
|
||||||
rust-tls = ["rustls", "actix-server/rust-tls"]
|
rust-tls = ["rustls", "actix-server/rust-tls"]
|
||||||
|
|
||||||
|
# unix domain sockets support
|
||||||
|
uds = ["actix-server/uds"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-service = "0.4.1"
|
actix-service = "0.4.1"
|
||||||
@ -75,11 +78,11 @@ actix-utils = "0.4.4"
|
|||||||
actix-router = "0.1.5"
|
actix-router = "0.1.5"
|
||||||
actix-rt = "0.2.4"
|
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.7"
|
||||||
actix-server = "0.5.1"
|
actix-server = "0.6.0"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.2"
|
||||||
actix-threadpool = "0.1.1"
|
actix-threadpool = "0.1.1"
|
||||||
awc = { version = "0.2.1", optional = true }
|
awc = { version = "0.2.2", optional = true }
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
derive_more = "0.15.0"
|
derive_more = "0.15.0"
|
||||||
@ -89,7 +92,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"
|
||||||
@ -104,7 +107,7 @@ rustls = { version = "0.15", optional = true }
|
|||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix = { version = "0.8.3" }
|
actix = { version = "0.8.3" }
|
||||||
actix-http = { version = "0.2.5", features=["ssl", "brotli", "flate2-zlib"] }
|
actix-http = { version = "0.2.5", features=["ssl", "brotli", "flate2-zlib"] }
|
||||||
actix-http-test = { version = "0.2.2", features=["ssl"] }
|
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||||
rand = "0.7"
|
rand = "0.7"
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
|
@ -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(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -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;
|
||||||
@ -57,7 +59,7 @@ pub struct ChunkedReadFile {
|
|||||||
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
|
||||||
///
|
///
|
||||||
@ -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
|
||||||
|
@ -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")
|
||||||
|
@ -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 {
|
||||||
|
@ -26,13 +26,13 @@ actix-utils = "0.4.0"
|
|||||||
actix-router = "0.1.2"
|
actix-router = "0.1.2"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-http = "0.2.0"
|
actix-http = "0.2.0"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.2"
|
||||||
|
|
||||||
bytes = "0.4"
|
bytes = "0.4"
|
||||||
futures = "0.1.25"
|
futures = "0.1.25"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
actix-server = { version = "0.6.0", features=["ssl"] }
|
||||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||||
|
@ -3,7 +3,7 @@ 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,
|
||||||
@ -12,7 +12,7 @@ pub(crate) type BoxedHttpService<Req> = Box<
|
|||||||
>;
|
>;
|
||||||
|
|
||||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||||
NewService<
|
dyn NewService<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Req,
|
Request = Req,
|
||||||
Response = (),
|
Response = (),
|
||||||
|
@ -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;
|
||||||
|
@ -1,5 +1,12 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.7] - 2019-07-18
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add support for downcasting response errors #986
|
||||||
|
|
||||||
|
|
||||||
## [0.2.6] - 2019-07-17
|
## [0.2.6] - 2019-07-17
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http"
|
name = "actix-http"
|
||||||
version = "0.2.5"
|
version = "0.2.7"
|
||||||
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"
|
||||||
@ -48,7 +48,7 @@ actix-service = "0.4.1"
|
|||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-connect = "0.2.1"
|
actix-connect = "0.2.1"
|
||||||
actix-utils = "0.4.4"
|
actix-utils = "0.4.4"
|
||||||
actix-server-config = "0.1.1"
|
actix-server-config = "0.1.2"
|
||||||
actix-threadpool = "0.1.1"
|
actix-threadpool = "0.1.1"
|
||||||
|
|
||||||
base64 = "0.10"
|
base64 = "0.10"
|
||||||
@ -97,9 +97,9 @@ chrono = "0.4.6"
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
actix-server = { version = "0.6.0", features=["ssl"] }
|
||||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
actix-http-test = { version = "0.2.4", features=["ssl"] }
|
||||||
env_logger = "0.6"
|
env_logger = "0.6"
|
||||||
serde_derive = "1.0"
|
serde_derive = "1.0"
|
||||||
openssl = { version="0.10" }
|
openssl = { version="0.10" }
|
||||||
|
@ -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)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -130,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,
|
||||||
>,
|
>,
|
||||||
@ -192,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,
|
||||||
>,
|
>,
|
||||||
|
@ -162,16 +162,21 @@ impl ServiceConfig {
|
|||||||
pub fn set_date(&self, dst: &mut BytesMut) {
|
pub fn set_date(&self, dst: &mut BytesMut) {
|
||||||
let mut buf: [u8; 39] = [0; 39];
|
let mut buf: [u8; 39] = [0; 39];
|
||||||
buf[..6].copy_from_slice(b"date: ");
|
buf[..6].copy_from_slice(b"date: ");
|
||||||
buf[6..35].copy_from_slice(&self.0.timer.date().bytes);
|
self.0
|
||||||
|
.timer
|
||||||
|
.set_date(|date| buf[6..35].copy_from_slice(&date.bytes));
|
||||||
buf[35..].copy_from_slice(b"\r\n\r\n");
|
buf[35..].copy_from_slice(b"\r\n\r\n");
|
||||||
dst.extend_from_slice(&buf);
|
dst.extend_from_slice(&buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn set_date_header(&self, dst: &mut BytesMut) {
|
pub(crate) fn set_date_header(&self, dst: &mut BytesMut) {
|
||||||
dst.extend_from_slice(&self.0.timer.date().bytes);
|
self.0
|
||||||
|
.timer
|
||||||
|
.set_date(|date| dst.extend_from_slice(&date.bytes));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone)]
|
||||||
struct Date {
|
struct Date {
|
||||||
bytes: [u8; DATE_VALUE_LENGTH],
|
bytes: [u8; DATE_VALUE_LENGTH],
|
||||||
pos: usize,
|
pos: usize,
|
||||||
@ -215,10 +220,6 @@ impl DateServiceInner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_ref(&self) -> &Option<(Date, Instant)> {
|
|
||||||
unsafe { &*self.current.get() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reset(&self) {
|
fn reset(&self) {
|
||||||
unsafe { (&mut *self.current.get()).take() };
|
unsafe { (&mut *self.current.get()).take() };
|
||||||
}
|
}
|
||||||
@ -236,7 +237,7 @@ impl DateService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn check_date(&self) {
|
fn check_date(&self) {
|
||||||
if self.0.get_ref().is_none() {
|
if unsafe { (&*self.0.current.get()).is_none() } {
|
||||||
self.0.update();
|
self.0.update();
|
||||||
|
|
||||||
// periodic date update
|
// periodic date update
|
||||||
@ -252,14 +253,12 @@ impl DateService {
|
|||||||
|
|
||||||
fn now(&self) -> Instant {
|
fn now(&self) -> Instant {
|
||||||
self.check_date();
|
self.check_date();
|
||||||
self.0.get_ref().as_ref().unwrap().1
|
unsafe { (&*self.0.current.get()).as_ref().unwrap().1 }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn date(&self) -> &Date {
|
fn set_date<F: FnMut(&Date)>(&self, mut f: F) {
|
||||||
self.check_date();
|
self.check_date();
|
||||||
|
f(&unsafe { (&*self.0.current.get()).as_ref().unwrap().0 })
|
||||||
let item = self.0.get_ref().as_ref().unwrap();
|
|
||||||
&item.0
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ 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: &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.
|
||||||
|
@ -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;
|
||||||
|
|
||||||
|
@ -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;
|
||||||
|
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
//! Error and Result module
|
//! Error and Result module
|
||||||
|
use std::any::TypeId;
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::str::Utf8Error;
|
use std::str::Utf8Error;
|
||||||
@ -43,14 +44,19 @@ 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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Similar to `as_response_error` but downcasts.
|
||||||
|
pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> {
|
||||||
|
ResponseError::downcast_ref(self.cause.as_ref())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Error that can be converted to `Response`
|
/// Error that can be converted to `Response`
|
||||||
@ -73,6 +79,25 @@ pub trait ResponseError: fmt::Debug + fmt::Display {
|
|||||||
);
|
);
|
||||||
resp.set_body(Body::from(buf))
|
resp.set_body(Body::from(buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
fn __private_get_type_id__(&self) -> TypeId
|
||||||
|
where
|
||||||
|
Self: 'static,
|
||||||
|
{
|
||||||
|
TypeId::of::<Self>()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseError + 'static {
|
||||||
|
/// Downcasts a response error to a specific type.
|
||||||
|
pub fn downcast_ref<T: ResponseError + 'static>(&self) -> Option<&T> {
|
||||||
|
if self.__private_get_type_id__() == TypeId::of::<T>() {
|
||||||
|
unsafe { Some(&*(self as *const ResponseError as *const T)) }
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for Error {
|
impl fmt::Display for Error {
|
||||||
@ -1044,6 +1069,16 @@ mod tests {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_error_casting() {
|
||||||
|
let err = PayloadError::Overflow;
|
||||||
|
let resp_err: &ResponseError = &err;
|
||||||
|
let err = resp_err.downcast_ref::<PayloadError>().unwrap();
|
||||||
|
assert_eq!(err.to_string(), "A payload reached size limit.");
|
||||||
|
let not_err = resp_err.downcast_ref::<ContentTypeError>();
|
||||||
|
assert!(not_err.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_error_helpers() {
|
fn test_error_helpers() {
|
||||||
let r: Response = ErrorBadRequest("err").into();
|
let r: Response = ErrorBadRequest("err").into();
|
||||||
|
@ -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)
|
||||||
|
@ -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');
|
||||||
}
|
}
|
||||||
|
@ -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,7 +254,7 @@ 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),
|
||||||
|
@ -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 {
|
||||||
|
@ -52,6 +52,9 @@ impl Response<Body> {
|
|||||||
#[inline]
|
#[inline]
|
||||||
pub fn from_error(error: Error) -> Response {
|
pub fn from_error(error: Error) -> Response {
|
||||||
let mut resp = error.as_response_error().render_response();
|
let mut resp = error.as_response_error().render_response();
|
||||||
|
if resp.head.status == StatusCode::INTERNAL_SERVER_ERROR {
|
||||||
|
error!("Internal Server Error: {:?}", error);
|
||||||
|
}
|
||||||
resp.error = Some(error);
|
resp.error = Some(error);
|
||||||
resp
|
resp
|
||||||
}
|
}
|
||||||
|
@ -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,7 +278,7 @@ 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,
|
||||||
@ -466,18 +466,20 @@ where
|
|||||||
State::Unknown(ref mut data) => {
|
State::Unknown(ref mut data) => {
|
||||||
if let Some(ref mut item) = data {
|
if let Some(ref mut item) = data {
|
||||||
loop {
|
loop {
|
||||||
unsafe {
|
// Safety - we only write to the returned slice.
|
||||||
let b = item.1.bytes_mut();
|
let b = unsafe { item.1.bytes_mut() };
|
||||||
let n = try_ready!(item.0.poll_read(b));
|
let n = try_ready!(item.0.poll_read(b));
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return Ok(Async::Ready(()));
|
return Ok(Async::Ready(()));
|
||||||
}
|
}
|
||||||
item.1.advance_mut(n);
|
// Safety - we know that 'n' bytes have
|
||||||
|
// been initialized via the contract of
|
||||||
|
// 'poll_read'
|
||||||
|
unsafe { item.1.advance_mut(n) };
|
||||||
if item.1.len() >= HTTP2_PREFACE.len() {
|
if item.1.len() >= HTTP2_PREFACE.len() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
panic!()
|
panic!()
|
||||||
}
|
}
|
||||||
|
@ -203,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 {
|
||||||
|
@ -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 {
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
#![allow(clippy::borrow_interior_mutable_const)]
|
||||||
|
|
||||||
mod error;
|
mod error;
|
||||||
mod extractor;
|
mod extractor;
|
||||||
mod server;
|
mod server;
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
//! Multipart payload support
|
//! Multipart payload support
|
||||||
use std::cell::{Cell, RefCell, UnsafeCell};
|
use std::cell::{Cell, RefCell, RefMut};
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::{cmp, fmt};
|
use std::{cmp, fmt};
|
||||||
@ -112,7 +112,7 @@ impl Stream for Multipart {
|
|||||||
Err(err)
|
Err(err)
|
||||||
} else if self.safety.current() {
|
} else if self.safety.current() {
|
||||||
let mut inner = self.inner.as_mut().unwrap().borrow_mut();
|
let mut inner = self.inner.as_mut().unwrap().borrow_mut();
|
||||||
if let Some(payload) = inner.payload.get_mut(&self.safety) {
|
if let Some(mut payload) = inner.payload.get_mut(&self.safety) {
|
||||||
payload.poll_stream()?;
|
payload.poll_stream()?;
|
||||||
}
|
}
|
||||||
inner.poll(&self.safety)
|
inner.poll(&self.safety)
|
||||||
@ -265,12 +265,12 @@ impl InnerMultipart {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let headers = if let Some(payload) = self.payload.get_mut(safety) {
|
let headers = if let Some(mut payload) = self.payload.get_mut(safety) {
|
||||||
match self.state {
|
match self.state {
|
||||||
// read until first boundary
|
// read until first boundary
|
||||||
InnerState::FirstBoundary => {
|
InnerState::FirstBoundary => {
|
||||||
match InnerMultipart::skip_until_boundary(
|
match InnerMultipart::skip_until_boundary(
|
||||||
payload,
|
&mut *payload,
|
||||||
&self.boundary,
|
&self.boundary,
|
||||||
)? {
|
)? {
|
||||||
Some(eof) => {
|
Some(eof) => {
|
||||||
@ -286,7 +286,10 @@ impl InnerMultipart {
|
|||||||
}
|
}
|
||||||
// read boundary
|
// read boundary
|
||||||
InnerState::Boundary => {
|
InnerState::Boundary => {
|
||||||
match InnerMultipart::read_boundary(payload, &self.boundary)? {
|
match InnerMultipart::read_boundary(
|
||||||
|
&mut *payload,
|
||||||
|
&self.boundary,
|
||||||
|
)? {
|
||||||
None => return Ok(Async::NotReady),
|
None => return Ok(Async::NotReady),
|
||||||
Some(eof) => {
|
Some(eof) => {
|
||||||
if eof {
|
if eof {
|
||||||
@ -303,7 +306,7 @@ impl InnerMultipart {
|
|||||||
|
|
||||||
// read field headers for next field
|
// read field headers for next field
|
||||||
if self.state == InnerState::Headers {
|
if self.state == InnerState::Headers {
|
||||||
if let Some(headers) = InnerMultipart::read_headers(payload)? {
|
if let Some(headers) = InnerMultipart::read_headers(&mut *payload)? {
|
||||||
self.state = InnerState::Boundary;
|
self.state = InnerState::Boundary;
|
||||||
headers
|
headers
|
||||||
} else {
|
} else {
|
||||||
@ -411,14 +414,15 @@ impl Stream for Field {
|
|||||||
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
||||||
if self.safety.current() {
|
if self.safety.current() {
|
||||||
let mut inner = self.inner.borrow_mut();
|
let mut inner = self.inner.borrow_mut();
|
||||||
if let Some(payload) = inner.payload.as_ref().unwrap().get_mut(&self.safety)
|
if let Some(mut payload) =
|
||||||
|
inner.payload.as_ref().unwrap().get_mut(&self.safety)
|
||||||
{
|
{
|
||||||
payload.poll_stream()?;
|
payload.poll_stream()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
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,14 +537,12 @@ 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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
return if let Some(idx) = twoway::find_bytes(&payload.buf[pos..], b"\r") {
|
return if let Some(idx) = twoway::find_bytes(&payload.buf[pos..], b"\r") {
|
||||||
@ -557,7 +559,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 {
|
||||||
@ -584,12 +586,13 @@ impl InnerField {
|
|||||||
return Ok(Async::Ready(None));
|
return Ok(Async::Ready(None));
|
||||||
}
|
}
|
||||||
|
|
||||||
let result = if let Some(payload) = self.payload.as_ref().unwrap().get_mut(s) {
|
let result = if let Some(mut payload) = self.payload.as_ref().unwrap().get_mut(s)
|
||||||
|
{
|
||||||
if !self.eof {
|
if !self.eof {
|
||||||
let res = if let Some(ref mut len) = self.length {
|
let res = if let Some(ref mut len) = self.length {
|
||||||
InnerField::read_len(payload, len)?
|
InnerField::read_len(&mut *payload, len)?
|
||||||
} else {
|
} else {
|
||||||
InnerField::read_stream(payload, &self.boundary)?
|
InnerField::read_stream(&mut *payload, &self.boundary)?
|
||||||
};
|
};
|
||||||
|
|
||||||
match res {
|
match res {
|
||||||
@ -620,7 +623,7 @@ impl InnerField {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct PayloadRef {
|
struct PayloadRef {
|
||||||
payload: Rc<UnsafeCell<PayloadBuffer>>,
|
payload: Rc<RefCell<PayloadBuffer>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PayloadRef {
|
impl PayloadRef {
|
||||||
@ -630,15 +633,12 @@ impl PayloadRef {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_mut<'a, 'b>(&'a self, s: &'b Safety) -> Option<&'a mut PayloadBuffer>
|
fn get_mut<'a, 'b>(&'a self, s: &'b Safety) -> Option<RefMut<'a, PayloadBuffer>>
|
||||||
where
|
where
|
||||||
'a: 'b,
|
'a: 'b,
|
||||||
{
|
{
|
||||||
// Unsafe: Invariant is inforced by Safety Safety is used as ref counter,
|
|
||||||
// only top most ref can have mutable access to payload.
|
|
||||||
if s.current() {
|
if s.current() {
|
||||||
let payload: &mut PayloadBuffer = unsafe { &mut *self.payload.get() };
|
Some(self.payload.borrow_mut())
|
||||||
Some(payload)
|
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
@ -342,7 +342,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
(SessionStatus::Purged, _) => {
|
(SessionStatus::Purged, _) => {
|
||||||
inner.remove_cookie(&mut res);
|
let _ = inner.remove_cookie(&mut res);
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
_ => res,
|
_ => res,
|
||||||
|
@ -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();
|
||||||
|
@ -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;
|
||||||
|
@ -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),
|
||||||
|
@ -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,11 +92,9 @@ 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() {
|
||||||
match bound {
|
if let syn::TypeParamBound::Trait(bound) = bound {
|
||||||
syn::TypeParamBound::Trait(bound) => {
|
|
||||||
for bound in bound.path.segments.iter() {
|
for bound in bound.path.segments.iter() {
|
||||||
if bound.ident == "Future" {
|
if bound.ident == "Future" {
|
||||||
guess = ResourceType::Async;
|
guess = ResourceType::Async;
|
||||||
@ -107,22 +105,14 @@ fn guess_resource_type(typ: &syn::Type) -> ResourceType {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
|
|
||||||
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()),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -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 {
|
||||||
|
@ -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,
|
||||||
>,
|
>,
|
||||||
@ -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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
#![allow(clippy::borrow_interior_mutable_const)]
|
||||||
//! An HTTP Client
|
//! An HTTP Client
|
||||||
//!
|
//!
|
||||||
//! ```rust
|
//! ```rust
|
||||||
|
@ -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
|
||||||
|
@ -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
|
||||||
}
|
}
|
||||||
|
@ -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());
|
||||||
|
49
examples/uds.rs
Normal file
49
examples/uds.rs
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
use futures::IntoFuture;
|
||||||
|
|
||||||
|
use actix_web::{
|
||||||
|
get, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[get("/resource1/{name}/index.html")]
|
||||||
|
fn index(req: HttpRequest, name: web::Path<String>) -> String {
|
||||||
|
println!("REQ: {:?}", req);
|
||||||
|
format!("Hello: {}!\r\n", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn index_async(req: HttpRequest) -> impl IntoFuture<Item = &'static str, Error = Error> {
|
||||||
|
println!("REQ: {:?}", req);
|
||||||
|
Ok("Hello world!\r\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/")]
|
||||||
|
fn no_params() -> &'static str {
|
||||||
|
"Hello world!\r\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info");
|
||||||
|
env_logger::init();
|
||||||
|
|
||||||
|
HttpServer::new(|| {
|
||||||
|
App::new()
|
||||||
|
.wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
|
||||||
|
.wrap(middleware::Compress::default())
|
||||||
|
.wrap(middleware::Logger::default())
|
||||||
|
.service(index)
|
||||||
|
.service(no_params)
|
||||||
|
.service(
|
||||||
|
web::resource("/resource2/index.html")
|
||||||
|
.wrap(
|
||||||
|
middleware::DefaultHeaders::new().header("X-Version-R2", "0.3"),
|
||||||
|
)
|
||||||
|
.default_service(
|
||||||
|
web::route().to(|| HttpResponse::MethodNotAllowed()),
|
||||||
|
)
|
||||||
|
.route(web::get().to_async(index_async)),
|
||||||
|
)
|
||||||
|
.service(web::resource("/test1.html").to(|| "Test\r\n"))
|
||||||
|
})
|
||||||
|
.bind_uds("/Users/fafhrd91/uds-test")?
|
||||||
|
.workers(1)
|
||||||
|
.run()
|
||||||
|
}
|
@ -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>,
|
||||||
|
@ -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<dyn 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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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 {
|
||||||
|
@ -25,11 +25,7 @@ impl ConnectionInfo {
|
|||||||
Ref::map(req.extensions(), |e| e.get().unwrap())
|
Ref::map(req.extensions(), |e| e.get().unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(
|
#[allow(clippy::cognitive_complexity)]
|
||||||
clippy::cyclomatic_complexity,
|
|
||||||
clippy::cognitive_complexity,
|
|
||||||
clippy::borrow_interior_mutable_const
|
|
||||||
)]
|
|
||||||
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;
|
||||||
|
@ -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.
|
||||||
//!
|
//!
|
||||||
@ -77,6 +78,7 @@
|
|||||||
//! `c` compiler (default enabled)
|
//! `c` compiler (default enabled)
|
||||||
//! * `flate2-rust` - experimental rust based implementation for
|
//! * `flate2-rust` - experimental rust based implementation for
|
||||||
//! `gzip`, `deflate` compression.
|
//! `gzip`, `deflate` compression.
|
||||||
|
//! * `uds` - Unix domain support, enables `HttpServer::bind_uds()` method.
|
||||||
//!
|
//!
|
||||||
#![allow(clippy::type_complexity, clippy::new_without_default)]
|
#![allow(clippy::type_complexity, clippy::new_without_default)]
|
||||||
|
|
||||||
|
@ -107,7 +107,6 @@ where
|
|||||||
self.service.poll_ready()
|
self.service.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::borrow_interior_mutable_const)]
|
|
||||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||||
// negotiate content-encoding
|
// negotiate content-encoding
|
||||||
let encoding = if let Some(val) = req.headers().get(&ACCEPT_ENCODING) {
|
let encoding = if let Some(val) = req.headers().get(&ACCEPT_ENCODING) {
|
||||||
|
@ -125,7 +125,6 @@ where
|
|||||||
self.service.poll_ready()
|
self.service.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::borrow_interior_mutable_const)]
|
|
||||||
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
||||||
let inner = self.inner.clone();
|
let inner = self.inner.clone();
|
||||||
|
|
||||||
|
@ -18,7 +18,7 @@ pub enum ErrorHandlerResponse<B> {
|
|||||||
Future(Box<dyn 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.
|
||||||
///
|
///
|
||||||
|
@ -9,12 +9,13 @@ use actix_service::{Service, Transform};
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
|
use log::debug;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use time;
|
use time;
|
||||||
|
|
||||||
use crate::dev::{BodySize, MessageBody, ResponseBody};
|
use crate::dev::{BodySize, MessageBody, ResponseBody};
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
use crate::http::{HeaderName, HttpTryFrom};
|
use crate::http::{HeaderName, HttpTryFrom, StatusCode};
|
||||||
use crate::service::{ServiceRequest, ServiceResponse};
|
use crate::service::{ServiceRequest, ServiceResponse};
|
||||||
use crate::HttpResponse;
|
use crate::HttpResponse;
|
||||||
|
|
||||||
@ -202,6 +203,12 @@ where
|
|||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
let res = futures::try_ready!(self.fut.poll());
|
let res = futures::try_ready!(self.fut.poll());
|
||||||
|
|
||||||
|
if let Some(error) = res.response().error() {
|
||||||
|
if res.response().head().status != StatusCode::INTERNAL_SERVER_ERROR {
|
||||||
|
debug!("Error in response: {:?}", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(ref mut format) = self.format {
|
if let Some(ref mut format) = self.format {
|
||||||
for unit in &mut format.0 {
|
for unit in &mut format.0 {
|
||||||
unit.render_response(res.response());
|
unit.render_response(res.response());
|
||||||
@ -444,7 +451,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> {
|
||||||
|
@ -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
|
||||||
}
|
}
|
||||||
|
12
src/route.rs
12
src/route.rs
@ -13,7 +13,7 @@ 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,
|
||||||
@ -25,7 +25,7 @@ type BoxedRouteService<Req, Res> = Box<
|
|||||||
>;
|
>;
|
||||||
|
|
||||||
type BoxedRouteNewService<Req, Res> = Box<
|
type BoxedRouteNewService<Req, Res> = Box<
|
||||||
NewService<
|
dyn NewService<
|
||||||
Config = (),
|
Config = (),
|
||||||
Request = Req,
|
Request = Req,
|
||||||
Response = Res,
|
Response = Res,
|
||||||
@ -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())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -84,7 +84,7 @@ type RouteFuture = Box<
|
|||||||
|
|
||||||
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 {
|
||||||
@ -104,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 {
|
||||||
|
@ -23,7 +23,7 @@ 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<
|
||||||
@ -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>>>,
|
||||||
@ -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)>,
|
||||||
}
|
}
|
||||||
|
@ -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(|_| ()),
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@ -434,6 +434,38 @@ where
|
|||||||
}
|
}
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "uds")]
|
||||||
|
/// Start listening for incoming unix domain connections.
|
||||||
|
///
|
||||||
|
/// This method is available with `uds` feature.
|
||||||
|
pub fn bind_uds<A>(mut self, addr: A) -> io::Result<Self>
|
||||||
|
where
|
||||||
|
A: AsRef<std::path::Path>,
|
||||||
|
{
|
||||||
|
let cfg = self.config.clone();
|
||||||
|
let factory = self.factory.clone();
|
||||||
|
self.sockets.push(Socket {
|
||||||
|
scheme: "http",
|
||||||
|
addr: net::SocketAddr::new(
|
||||||
|
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
|
||||||
|
8080,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
self.builder = self.builder.bind_uds(
|
||||||
|
format!("actix-web-service-{:?}", addr.as_ref()),
|
||||||
|
addr,
|
||||||
|
move || {
|
||||||
|
let c = cfg.lock();
|
||||||
|
HttpService::build()
|
||||||
|
.keep_alive(c.keep_alive)
|
||||||
|
.client_timeout(c.client_timeout)
|
||||||
|
.finish(factory())
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F, I, S, B> HttpServer<F, I, S, B>
|
impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||||
|
@ -407,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 {
|
||||||
@ -476,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>
|
||||||
|
@ -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)]
|
||||||
|
@ -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 {
|
||||||
@ -192,7 +192,6 @@ pub struct UrlEncoded<U> {
|
|||||||
|
|
||||||
impl<U> UrlEncoded<U> {
|
impl<U> UrlEncoded<U> {
|
||||||
/// Create a new future to URL encode a request
|
/// Create a new future to URL encode a request
|
||||||
#[allow(clippy::borrow_interior_mutable_const)]
|
|
||||||
pub fn new(req: &HttpRequest, payload: &mut Payload) -> UrlEncoded<U> {
|
pub fn new(req: &HttpRequest, payload: &mut Payload) -> UrlEncoded<U> {
|
||||||
// check content type
|
// check content type
|
||||||
if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" {
|
if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" {
|
||||||
|
@ -298,7 +298,6 @@ where
|
|||||||
U: DeserializeOwned + 'static,
|
U: DeserializeOwned + 'static,
|
||||||
{
|
{
|
||||||
/// Create `JsonBody` for request.
|
/// Create `JsonBody` for request.
|
||||||
#[allow(clippy::borrow_interior_mutable_const)]
|
|
||||||
pub fn new(
|
pub fn new(
|
||||||
req: &HttpRequest,
|
req: &HttpRequest,
|
||||||
payload: &mut Payload,
|
payload: &mut Payload,
|
||||||
|
@ -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 {
|
||||||
|
@ -128,7 +128,7 @@ impl FromRequest for Bytes {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
||||||
let mut tmp;
|
let 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 {
|
||||||
@ -184,7 +184,7 @@ impl FromRequest for String {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
|
||||||
let mut tmp;
|
let 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 {
|
||||||
@ -298,7 +298,6 @@ pub struct HttpMessageBody {
|
|||||||
|
|
||||||
impl HttpMessageBody {
|
impl HttpMessageBody {
|
||||||
/// Create `MessageBody` for request.
|
/// Create `MessageBody` for request.
|
||||||
#[allow(clippy::borrow_interior_mutable_const)]
|
|
||||||
pub fn new(req: &HttpRequest, payload: &mut dev::Payload) -> HttpMessageBody {
|
pub fn new(req: &HttpRequest, payload: &mut dev::Payload) -> HttpMessageBody {
|
||||||
let mut len = None;
|
let mut len = None;
|
||||||
if let Some(l) = req.headers().get(&header::CONTENT_LENGTH) {
|
if let Some(l) = req.headers().get(&header::CONTENT_LENGTH) {
|
||||||
|
@ -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 {
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.2.4] - 2019-07-18
|
||||||
|
|
||||||
|
* Update actix-server to 0.6
|
||||||
|
|
||||||
## [0.2.3] - 2019-07-16
|
## [0.2.3] - 2019-07-16
|
||||||
|
|
||||||
* Add `delete`, `options`, `patch` methods to `TestServerRunner`
|
* Add `delete`, `options`, `patch` methods to `TestServerRunner`
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-http-test"
|
name = "actix-http-test"
|
||||||
version = "0.2.3"
|
version = "0.2.4"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix http test server"
|
description = "Actix http test server"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
@ -33,7 +33,7 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
|||||||
actix-codec = "0.1.2"
|
actix-codec = "0.1.2"
|
||||||
actix-rt = "0.2.2"
|
actix-rt = "0.2.2"
|
||||||
actix-service = "0.4.1"
|
actix-service = "0.4.1"
|
||||||
actix-server = "0.5.1"
|
actix-server = "0.6.0"
|
||||||
actix-utils = "0.4.1"
|
actix-utils = "0.4.1"
|
||||||
awc = "0.2.2"
|
awc = "0.2.2"
|
||||||
|
|
||||||
|
@ -12,6 +12,7 @@ use futures::future::lazy;
|
|||||||
use futures::{Future, IntoFuture, Stream};
|
use futures::{Future, IntoFuture, Stream};
|
||||||
use http::Method;
|
use http::Method;
|
||||||
use net2::TcpBuilder;
|
use net2::TcpBuilder;
|
||||||
|
use tokio_tcp::TcpStream;
|
||||||
|
|
||||||
thread_local! {
|
thread_local! {
|
||||||
static RT: RefCell<Inner> = {
|
static RT: RefCell<Inner> = {
|
||||||
@ -65,7 +66,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,8 +108,9 @@ 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<TcpStream>>(factory: F) -> TestServerRuntime {
|
||||||
let (tx, rx) = mpsc::channel();
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
// run server in separate thread
|
// run server in separate thread
|
||||||
@ -191,7 +193,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
|
||||||
|
Reference in New Issue
Block a user