1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-03 17:41:30 +02:00

Compare commits

...

84 Commits

Author SHA1 Message Date
2a2d7f5768 nightly clippy warnings 2019-07-17 15:53:51 +06:00
4092c7f326 clippy warnings 2019-07-17 15:08:30 +06:00
ef3e1037a8 bump version 2019-07-17 14:18:26 +06:00
baaa7b3fbb Replace ClonableService with local copy 2019-07-17 13:55:44 +06:00
32718b7e31 Expose factory traits and some clippy fixes (#983) 2019-07-17 12:58:42 +06:00
c01611d8b5 prepare actix-web release 2019-07-17 12:07:12 +06:00
7b1dcaffda cleanup deprecation warning for Box<dyn> 2019-07-17 11:44:39 +06:00
c65dbaf88e expose app's ResourceMap via resource_map method 2019-07-17 11:33:05 +06:00
c45728ac01 prep test server release 2019-07-16 10:21:52 +06:00
6f71409355 Add DELETE, PATCH, OPTIONS methods to TestServerRunner (#973) 2019-07-16 10:19:28 +06:00
8d17c8651f update bench link 2019-07-11 14:45:58 +06:00
b1143168e5 Impl Responder for (T, StatusCode) where T: Responder (#954) 2019-07-11 14:42:58 +06:00
69456991f6 update api doc example for client and add panic info for connection_info 2019-07-11 14:40:37 +06:00
f410f3330f prepare actix-session release 2019-07-08 23:25:51 +06:00
e1fcd203f8 Update the copyless version to 0.1.4 (#956)
< 0.1.4 failed to check for null when doing allocations which could lead to null dereferences.
2019-07-08 15:48:20 +06:00
0d8a4304a9 Drop a duplicated word (#958) 2019-07-05 20:46:55 +06:00
14cc5a5d6b Merge pull request #912 from Dowwie/master
updated actix-session to support login and logout functionality
2019-07-03 21:07:07 -04:00
287c2b1d18 Merge branch 'master' into master 2019-07-03 18:50:19 -04:00
7596ab69e0 reverted actix-web/CHANGES.md 2019-07-03 08:55:29 -04:00
1fdd77bffa reworded session info in CHANGES 2019-07-03 07:56:50 -04:00
2d424957fb updated version in Cargo to 0.2 2019-07-03 07:50:45 -04:00
dabc4fe00b updated actix-session/CHANGES with info 2019-07-03 07:50:11 -04:00
5bf5b0acd2 updated CHANGES with info about actix-session update 2019-07-03 07:46:46 -04:00
099a8ff7d8 updated session cookie to support login, logout, changes 2019-07-01 15:26:19 -04:00
a28b7139e6 prepare awc release 2019-07-01 11:34:57 +06:00
a0a469fe85 disable travis cargo cache 2019-07-01 11:33:11 +06:00
dbab55dd6b Bump rand crate version to 0.7 (#951) 2019-07-01 09:37:03 +06:00
d2eb1edac3 Actix-web client: Always append a colon after username in basic auth (#949)
* Always append a colon after username in basic auth

* Update CHANGES.md
2019-07-01 09:34:42 +06:00
5901dfee1a Fix link to actix-cors (#950) 2019-06-30 21:30:04 +06:00
0e05b37082 updated cookie session to update on change 2019-06-29 14:24:02 -04:00
37f4ce8604 Fixes typo in docs. (#948)
Small typo in docs.
2019-06-29 10:38:16 +06:00
12b5174850 update deps 2019-06-28 14:46:26 +06:00
b77ed193f7 prepare actix-web release 2019-06-28 14:41:56 +06:00
d286ccb4f5 Add on-connect callback #946 2019-06-28 14:34:26 +06:00
cac162aed7 update actix-http changes 2019-06-28 12:34:43 +06:00
a3a78ac6fb Do not set Content-Length header, let actix-http set it #930 2019-06-28 11:42:20 +06:00
596483ff55 prepare actix-web-actors release 2019-06-28 10:54:23 +06:00
768859513a Expose the max limit for payload sizes in Websocket Actors. #925 (#933)
* Expose the max limit for payload sizes in Websocket Actors.

* Revert to previous not-formatted code.

* Implement WebsocketContext::with_codec and make Codec Copy and Clone.

* Fix formatting.

* Fix formatting.
2019-06-28 10:49:03 +06:00
44bb79cd07 Call req.path() on Json extractor error only (#945)
* Call req.path() on Json extractor error only

* Cleanup len parse code
2019-06-28 10:44:53 +06:00
af9fb5d190 Support asynchronous data factories #850 2019-06-28 10:43:52 +06:00
50a9d9e2c5 Merge branch 'master' into master 2019-06-27 06:38:13 -04:00
c0c71f82c0 Fixes typo. (#940)
Small typo fix.
2019-06-25 23:23:36 +06:00
93855b889a Merge branch 'master' into master 2019-06-24 18:41:48 -04:00
fa7e0fe6df updated cookie.rs req to get_changes 2019-06-24 18:40:14 -04:00
b948f74b54 Extractor configuration Migration (#937)
added guide for Extractor configuration in MIGRATION.md
2019-06-24 07:16:04 +06:00
1a24ff8717 Add builder function for HTTP 429 Too Many Requests status (#931) 2019-06-21 13:06:29 +06:00
47fab0e393 Bump derive_more crate version to 0.15.0 in actix-cors (#927) 2019-06-19 16:41:42 +06:00
313ac48765 Use encoding_rs crate instead of unmaintained encoding crate (#922)
* Use encoding_rs crate instead of unmaintained encoding crate

* Update changelog
2019-06-18 12:43:25 +06:00
d7780d53c9 Fix typo in actix_web::web::Data::get_ref docstring (#921) 2019-06-18 07:27:23 +06:00
ad0e6f73b3 update version 2019-06-17 12:35:00 +06:00
546a8a58db remove cors and identity middlewares 2019-06-17 12:33:00 +06:00
acda1c075a prepare actix-web release 2019-06-17 12:23:30 +06:00
686e5f1595 update deps 2019-06-16 22:10:22 +06:00
d2b6502c7a prepare actix-http release 2019-06-16 21:59:22 +06:00
7c0f570845 Do not compress NoContent (204) responses #918 2019-06-16 21:54:17 +06:00
382d4ca216 Merge branch 'master' into master 2019-06-15 22:21:39 +06:00
eaa371db8b update migration 2019-06-15 22:20:46 +06:00
d293ae2a69 fix nested resource map registration #915 2019-06-15 22:12:20 +06:00
d7ec241fd0 re-export identity and cors middleware 2019-06-15 21:47:06 +06:00
cd323f2ff1 Move cors middleware to actix-cors crate 2019-06-15 09:34:16 +06:00
32a66a99bf reverting change to get_session due to side effects 2019-06-13 09:19:03 -04:00
73ae801a13 Merge branch 'master' of https://github.com/Dowwie/actix-web 2019-06-13 09:00:45 -04:00
ca4ed0932e made Session::get_session public 2019-06-13 08:59:59 -04:00
bf48798bce Content-Length is 0 for NamedFile HEAD request #914 2019-06-13 15:27:21 +06:00
9fc7c8b1af Merge branch 'master' into master 2019-06-12 23:53:36 +06:00
c8118e8411 fix path doc tests 2019-06-12 20:12:15 +06:00
65732197b8 modified so as to consider unanticipated state changes 2019-06-12 10:11:38 -04:00
959eef05ae updated actix-session to support login and logout functionality (renew and purge) 2019-06-12 08:03:27 -04:00
e7ba67e1a8 rename PathPayloadError and test for path config 2019-06-12 17:02:45 +06:00
13e618b128 Added initial support for PathConfig, allows setting custom error handler. (#903) 2019-06-12 16:49:56 +06:00
36e6f0cb4b add "put" and "sput" methods for test server (#909) 2019-06-12 16:47:00 +06:00
7450ae37a7 Re-apply patch from #637 #894 2019-06-12 16:45:05 +06:00
2ffda29f9b Allow to test an app that uses async actors #897 2019-06-12 16:15:06 +06:00
ff724e239d move identity service separate crate 2019-06-12 15:52:48 +06:00
Bob
ee769832cf get_identity from HttpMessage (#908)
* get_identity from HttpMessage

* more doc for RequestIdentity
2019-06-12 09:26:46 +06:00
c4b7980b4f Upgraded actix-web dependency and set default-features to false (#895) 2019-06-07 09:34:56 +06:00
bfbac4f875 Upgraded actix-web dependency and set default-features to false (#900) 2019-06-07 09:34:30 +06:00
53e2f8090f Mark default enabled package features in the docs (#890) 2019-06-06 11:14:56 +06:00
e399e01a22 update readme 2019-06-05 09:02:44 +06:00
d9a62c4bbf add App::register_data() 2019-06-05 08:43:39 +06:00
a548b69679 fmt 2019-06-05 08:43:13 +06:00
ae64475d98 test-server release 2019-06-05 08:27:25 +06:00
a342b1289d prep awc release 2019-06-05 08:14:00 +06:00
38f04b75a7 update deps 2019-06-04 22:36:10 +06:00
112 changed files with 1651 additions and 546 deletions

View File

@ -3,7 +3,7 @@ sudo: required
dist: trusty
cache:
cargo: true
# cargo: true
apt: true
matrix:
@ -26,7 +26,7 @@ before_install:
before_cache: |
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-04-02" ]]; then
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install cargo-tarpaulin
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
fi
# Add clippy

View File

@ -1,8 +1,67 @@
# Changes
## [1.0.0] - 2019-06-xx
## [1.0.4] - 2019-07-17
### Add
### Added
* 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
* Upgrade `rand` dependency version to 0.7
## [1.0.3] - 2019-06-28
### Added
* Support asynchronous data factories #850
### Changed
* Use `encoding_rs` crate instead of unmaintained `encoding` crate
## [1.0.2] - 2019-06-17
### Changed
* Move cors middleware to `actix-cors` crate.
* Move identity middleware to `actix-identity` crate.
## [1.0.1] - 2019-06-17
### Added
* Add support for PathConfig #903
* Add `middleware::identity::RequestIdentity` trait to `get_identity` from `HttpMessage`.
### Changed
* Move cors middleware to `actix-cors` crate.
* Move identity middleware to `actix-identity` crate.
* Disable default feature `secure-cookies`.
* Allow to test an app that uses async actors #897
* Re-apply patch from #637 #894
### Fixed
* HttpRequest::url_for is broken with nested scopes #915
## [1.0.0] - 2019-06-05
### Added
* Add `Scope::configure()` method.
@ -13,7 +72,7 @@
* Add macros for head, options, trace, connect and patch http methods
### Changes
### Changed
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
@ -31,7 +90,7 @@
* Add `Query<T>::from_query()` to extract parameters from a query string. #846
* `QueryConfig`, similar to `JsonConfig` for customizing error handling of query extractors.
### Changes
### Changed
* `JsonConfig` is now `Send + Sync`, this implies that `error_handler` must be `Send + Sync` too.
@ -46,7 +105,7 @@
* Allow to set/override app data on scope level
### Changes
### Changed
* `App::configure` take an `FnOnce` instead of `Fn`
* Upgrade actix-net crates

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web"
version = "1.0.0"
version = "1.0.4"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
readme = "README.md"
@ -31,9 +31,11 @@ members = [
".",
"awc",
"actix-http",
"actix-cors",
"actix-files",
"actix-framed",
"actix-session",
"actix-identity",
"actix-multipart",
"actix-web-actors",
"actix-web-codegen",
@ -41,7 +43,7 @@ members = [
]
[features]
default = ["brotli", "flate2-zlib", "secure-cookies", "client", "fail"]
default = ["brotli", "flate2-zlib", "client", "fail"]
# http client
client = ["awc"]
@ -68,26 +70,26 @@ rust-tls = ["rustls", "actix-server/rust-tls"]
[dependencies]
actix-codec = "0.1.2"
actix-service = "0.4.0"
actix-utils = "0.4.1"
actix-service = "0.4.1"
actix-utils = "0.4.4"
actix-router = "0.1.5"
actix-rt = "0.2.2"
actix-web-codegen = "0.1.1"
actix-http = "0.2.2"
actix-rt = "0.2.4"
actix-web-codegen = "0.1.2"
actix-http = "0.2.6"
actix-server = "0.5.1"
actix-server-config = "0.1.1"
actix-threadpool = "0.1.0"
awc = { version = "0.2.0", optional = true }
actix-threadpool = "0.1.1"
awc = { version = "0.2.1", optional = true }
bytes = "0.4"
derive_more = "0.14"
encoding = "0.2"
derive_more = "0.15.0"
encoding_rs = "0.8"
futures = "0.1.25"
hashbrown = "0.3.0"
hashbrown = "0.5.0"
log = "0.4"
mime = "0.3"
net2 = "0.2.33"
parking_lot = "0.8"
parking_lot = "0.9"
regex = "1.0"
serde = { version = "1.0", features=["derive"] }
serde_json = "1.0"
@ -100,10 +102,10 @@ openssl = { version="0.10", optional = true }
rustls = { version = "0.15", optional = true }
[dev-dependencies]
actix-http = { version = "0.2.2", features=["ssl", "brotli", "flate2-zlib"] }
actix-http-test = { version = "0.2.0", features=["ssl"] }
actix-files = { version = "0.1.1" }
rand = "0.6"
actix = { version = "0.8.3" }
actix-http = { version = "0.2.5", features=["ssl", "brotli", "flate2-zlib"] }
actix-http-test = { version = "0.2.2", features=["ssl"] }
rand = "0.7"
env_logger = "0.6"
serde_derive = "1.0"
tokio-timer = "0.2.8"

View File

@ -1,4 +1,93 @@
## 1.0
## 1.0.1
* Cors middleware has been moved to `actix-cors` crate
instead of
```rust
use actix_web::middleware::cors::Cors;
```
use
```rust
use actix_cors::Cors;
```
* Identity middleware has been moved to `actix-identity` crate
instead of
```rust
use actix_web::middleware::identity::{Identity, CookieIdentityPolicy, IdentityService};
```
use
```rust
use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
```
## 1.0.0
* Extractor configuration. In version 1.0 this is handled with the new `Data` mechanism for both setting and retrieving the configuration
instead of
```rust
#[derive(Default)]
struct ExtractorConfig {
config: String,
}
impl FromRequest for YourExtractor {
type Config = ExtractorConfig;
type Result = Result<YourExtractor, Error>;
fn from_request(req: &HttpRequest, cfg: &Self::Config) -> Self::Result {
println!("use the config: {:?}", cfg.config);
...
}
}
App::new().resource("/route_with_config", |r| {
r.post().with_config(handler_fn, |cfg| {
cfg.0.config = "test".to_string();
})
})
```
use the HttpRequest to get the configuration like any other `Data` with `req.app_data::<C>()` and set it with the `data()` method on the `resource`
```rust
#[derive(Default)]
struct ExtractorConfig {
config: String,
}
impl FromRequest for YourExtractor {
type Error = Error;
type Future = Result<Self, Self::Error>;
type Config = ExtractorConfig;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let cfg = req.app_data::<ExtractorConfig>();
println!("config data?: {:?}", cfg.unwrap().role);
...
}
}
App::new().service(
resource("/route_with_config")
.data(ExtractorConfig {
config: "test".to_string(),
})
.route(post().to(handler_fn)),
)
```
* Resource registration. 1.0 version uses generalized resource
registration via `.service()` method.

View File

@ -11,7 +11,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
* Multipart streams
* Static assets
* SSL support with OpenSSL or Rustls
* Middlewares ([Logger, Session, CORS, CSRF, etc](https://actix.rs/docs/middleware/))
* Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
* Supports [Actix actor framework](https://github.com/actix/actix)
@ -22,7 +22,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
* [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-web](https://crates.io/crates/actix-web)
* Minimum supported Rust version: 1.32 or later
* Minimum supported Rust version: 1.34 or later
## Example
@ -61,7 +61,7 @@ You may consider checking out
## Benchmarks
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext)
* [TechEmpower Framework Benchmark](https://www.techempower.com/benchmarks/#section=data-r18)
## License

9
actix-cors/CHANGES.md Normal file
View File

@ -0,0 +1,9 @@
# Changes
## [0.1.1] - unreleased
* Bump `derive_more` crate version to 0.15.0
## [0.1.0] - 2019-06-15
* Move cors middleware to separate crate

23
actix-cors/Cargo.toml Normal file
View File

@ -0,0 +1,23 @@
[package]
name = "actix-cors"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Cross-origin resource sharing (CORS) for Actix applications."
readme = "README.md"
keywords = ["web", "framework"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-cors/"
license = "MIT/Apache-2.0"
edition = "2018"
#workspace = ".."
[lib]
name = "actix_cors"
path = "src/lib.rs"
[dependencies]
actix-web = "1.0.0"
actix-service = "0.4.0"
derive_more = "0.15.0"
futures = "0.1.25"

1
actix-cors/LICENSE-APACHE Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-cors/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

9
actix-cors/README.md Normal file
View File

@ -0,0 +1,9 @@
# Identity service for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-identity)](https://crates.io/crates/actix-identity) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [User Guide](https://actix.rs/docs/)
* [API Documentation](https://docs.rs/actix-cors/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-cors](https://crates.io/crates/actix-cors)
* Minimum supported Rust version: 1.34 or later

View File

@ -1,3 +1,4 @@
#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)]
//! Cross-origin resource sharing (CORS) for Actix applications
//!
//! CORS middleware could be used with application and with resource.
@ -7,7 +8,7 @@
//! # Example
//!
//! ```rust
//! use actix_web::middleware::cors::Cors;
//! use actix_cors::Cors;
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
//!
//! fn index(req: HttpRequest) -> &'static str {
@ -42,17 +43,15 @@ use std::iter::FromIterator;
use std::rc::Rc;
use actix_service::{IntoTransform, Service, Transform};
use actix_web::dev::{RequestHead, ServiceRequest, ServiceResponse};
use actix_web::error::{Error, ResponseError, Result};
use actix_web::http::header::{self, HeaderName, HeaderValue};
use actix_web::http::{self, HttpTryFrom, Method, StatusCode, Uri};
use actix_web::HttpResponse;
use derive_more::Display;
use futures::future::{ok, Either, Future, FutureResult};
use futures::Poll;
use crate::dev::RequestHead;
use crate::error::{Error, ResponseError, Result};
use crate::http::header::{self, HeaderName, HeaderValue};
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
use crate::service::{ServiceRequest, ServiceResponse};
use crate::HttpResponse;
/// A set of errors that can occur during processing CORS
#[derive(Debug, Display)]
pub enum CorsError {
@ -152,11 +151,11 @@ impl<T> AllOrSome<T> {
/// # Example
///
/// ```rust
/// use actix_cors::Cors;
/// use actix_web::http::header;
/// use actix_web::middleware::cors;
///
/// # fn main() {
/// let cors = cors::Cors::new()
/// let cors = Cors::new()
/// .allowed_origin("https://www.rust-lang.org/")
/// .allowed_methods(vec!["GET", "POST"])
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
@ -164,6 +163,7 @@ impl<T> AllOrSome<T> {
/// .max_age(3600);
/// # }
/// ```
#[derive(Default)]
pub struct Cors {
cors: Option<Inner>,
methods: bool,
@ -587,10 +587,10 @@ impl Inner {
}
Err(CorsError::BadOrigin)
} else {
return match self.origins {
match self.origins {
AllOrSome::All => Ok(()),
_ => Err(CorsError::MissingOrigin),
};
}
}
}
@ -665,7 +665,7 @@ impl Inner {
}
Err(CorsError::BadRequestHeaders)
} else {
return Ok(());
Ok(())
}
}
}
@ -683,7 +683,7 @@ where
type Error = Error;
type Future = Either<
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> {
@ -806,9 +806,9 @@ where
#[cfg(test)]
mod tests {
use actix_service::{IntoService, Transform};
use actix_web::test::{self, block_on, TestRequest};
use super::*;
use crate::test::{self, block_on, TestRequest};
impl Cors {
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>

View File

@ -1,5 +1,16 @@
# Changes
## [0.1.3] - 2019-06-28
* Do not set `Content-Length` header, let actix-http set it #930
## [0.1.2] - 2019-06-13
* Content-Length is 0 for NamedFile HEAD request #914
* Fix ring dependency from actix-web default features for #741
## [0.1.1] - 2019-06-01
* Static files are incorrectly served as both chunked and with length #812

View File

@ -1,6 +1,6 @@
[package]
name = "actix-files"
version = "0.1.1"
version = "0.1.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Static files support for actix web."
readme = "README.md"
@ -18,13 +18,13 @@ name = "actix_files"
path = "src/lib.rs"
[dependencies]
actix-web = "1.0.0-rc"
actix-http = "0.2.3"
actix-service = "0.4.0"
actix-web = { version = "1.0.2", default-features = false }
actix-http = "0.2.4"
actix-service = "0.4.1"
bitflags = "1"
bytes = "0.4"
futures = "0.1.25"
derive_more = "0.14"
derive_more = "0.15.0"
log = "0.4"
mime = "0.3"
mime_guess = "2.0.0-alpha"
@ -32,4 +32,4 @@ percent-encoding = "1.0"
v_htmlescape = "0.4"
[dev-dependencies]
actix-web = { version = "1.0.0-rc", features=["ssl"] }
actix-web = { version = "1.0.2", features=["ssl"] }

View File

@ -1,3 +1,5 @@
#![allow(clippy::borrow_interior_mutable_const, clippy::type_complexity)]
//! Static files support
use std::cell::RefCell;
use std::fmt::Write;
@ -50,14 +52,14 @@ pub struct ChunkedReadFile {
size: u64,
offset: u64,
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,
}
fn handle_error(err: BlockingError<io::Error>) -> Error {
match err {
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 =
Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>;
dyn Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>;
/// A directory; responds with the generated directory listing.
#[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
///
@ -370,7 +372,7 @@ impl NewService for Files {
type Error = Error;
type Service = FilesService;
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 {
let mut srv = FilesService {
@ -416,7 +418,7 @@ impl FilesService {
req: ServiceRequest,
) -> Either<
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);
if let Some(ref mut default) = self.default {
@ -433,7 +435,7 @@ impl Service for FilesService {
type Error = Error;
type Future = Either<
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> {
@ -473,7 +475,7 @@ impl Service for FilesService {
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 {
let dir = Directory::new(self.directory.clone(), path);
@ -481,7 +483,7 @@ impl Service for FilesService {
let x = (self.renderer)(&dir, &req);
match x {
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 {
Either::A(ok(ServiceResponse::from_err(
@ -855,6 +857,8 @@ mod tests {
#[test]
fn test_named_file_content_length_headers() {
// use actix_web::body::{MessageBody, ResponseBody};
let mut srv = test::init_service(
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
);
@ -864,16 +868,15 @@ mod tests {
.uri("/t%65st/tests/test.binary")
.header(header::RANGE, "bytes=10-20")
.to_request();
let response = test::call_service(&mut srv, request);
let _response = test::call_service(&mut srv, request);
let contentlength = response
.headers()
.get(header::CONTENT_LENGTH)
.unwrap()
.to_str()
.unwrap();
assert_eq!(contentlength, "11");
// let contentlength = response
// .headers()
// .get(header::CONTENT_LENGTH)
// .unwrap()
// .to_str()
// .unwrap();
// assert_eq!(contentlength, "11");
// Invalid range header
let request = TestRequest::get()
@ -888,16 +891,15 @@ mod tests {
.uri("/t%65st/tests/test.binary")
// .no_default_headers()
.to_request();
let response = test::call_service(&mut srv, request);
let _response = test::call_service(&mut srv, request);
let contentlength = response
.headers()
.get(header::CONTENT_LENGTH)
.unwrap()
.to_str()
.unwrap();
assert_eq!(contentlength, "100");
// let contentlength = response
// .headers()
// .get(header::CONTENT_LENGTH)
// .unwrap()
// .to_str()
// .unwrap();
// assert_eq!(contentlength, "100");
// chunked
let request = TestRequest::get()
@ -926,6 +928,29 @@ mod tests {
assert_eq!(bytes.freeze(), data);
}
#[test]
fn test_head_content_length_headers() {
let mut srv = test::init_service(
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
);
// Valid range header
let request = TestRequest::default()
.method(Method::HEAD)
.uri("/t%65st/tests/test.binary")
.to_request();
let _response = test::call_service(&mut srv, request);
// TODO: fix check
// let contentlength = response
// .headers()
// .get(header::CONTENT_LENGTH)
// .unwrap()
// .to_str()
// .unwrap();
// assert_eq!(contentlength, "100");
}
#[test]
fn test_static_files_with_spaces() {
let mut srv = test::init_service(

View File

@ -24,8 +24,8 @@ use crate::ChunkedReadFile;
bitflags! {
pub(crate) struct Flags: u32 {
const ETAG = 0b00000001;
const LAST_MD = 0b00000010;
const ETAG = 0b0000_0001;
const LAST_MD = 0b0000_0010;
}
}
@ -311,8 +311,8 @@ impl Responder for NamedFile {
return Ok(resp.streaming(reader));
}
match req.method() {
&Method::HEAD | &Method::GET => (),
match *req.method() {
Method::HEAD | Method::GET => (),
_ => {
return Ok(HttpResponse::MethodNotAllowed()
.header(header::CONTENT_TYPE, "text/plain")
@ -414,17 +414,12 @@ impl Responder for NamedFile {
};
};
resp.header(header::CONTENT_LENGTH, format!("{}", length));
if precondition_failed {
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish());
} else if not_modified {
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
}
if *req.method() == Method::HEAD {
Ok(resp.finish())
} else {
let reader = ChunkedReadFile {
offset,
size: length,
@ -437,5 +432,4 @@ impl Responder for NamedFile {
};
Ok(resp.body(SizedStream::new(length, reader)))
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -140,7 +140,7 @@ where
type Request = FramedRequest<Io, S>;
type Response = ();
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> {
Ok(Async::Ready(()))

View File

@ -1,5 +1,34 @@
# Changes
## [0.2.6] - 2019-07-17
### Changed
* Replace `ClonableService` with local copy
* Upgrade `rand` dependency version to 0.7
## [0.2.5] - 2019-06-28
### Added
* Add `on-connect` callback, `HttpServiceBuilder::on_connect()` #946
### Changed
* Use `encoding_rs` crate instead of unmaintained `encoding` crate
* Add `Copy` and `Clone` impls for `ws::Codec`
## [0.2.4] - 2019-06-16
### Fixed
* Do not compress NoContent (204) responses #918
## [0.2.3] - 2019-06-02
### Added
@ -76,7 +105,7 @@
## [0.1.1] - 2019-04-19
### Changes
### Changed
* Cookie::max_age() accepts value in seconds

View File

@ -1,6 +1,6 @@
[package]
name = "actix-http"
version = "0.2.3"
version = "0.2.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http primitives"
readme = "README.md"
@ -44,23 +44,23 @@ fail = ["failure"]
secure-cookies = ["ring"]
[dependencies]
actix-service = "0.4.0"
actix-service = "0.4.1"
actix-codec = "0.1.2"
actix-connect = "0.2.0"
actix-utils = "0.4.1"
actix-connect = "0.2.1"
actix-utils = "0.4.4"
actix-server-config = "0.1.1"
actix-threadpool = "0.1.0"
actix-threadpool = "0.1.1"
base64 = "0.10"
bitflags = "1.0"
bytes = "0.4"
byteorder = "1.2"
copyless = "0.1.2"
derive_more = "0.14"
copyless = "0.1.4"
derive_more = "0.15.0"
either = "1.5.2"
encoding = "0.2"
encoding_rs = "0.8"
futures = "0.1.25"
hashbrown = "0.3.0"
hashbrown = "0.5.0"
h2 = "0.1.16"
http = "0.1.17"
httparse = "1.3"
@ -70,7 +70,7 @@ language-tags = "0.2"
log = "0.4"
mime = "0.3"
percent-encoding = "1.0"
rand = "0.6"
rand = "0.7"
regex = "1.0"
serde = "1.0"
serde_json = "1.0"

View File

@ -1,5 +1,6 @@
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use actix_codec::Framed;
use actix_server_config::ServerConfig as SrvConfig;
@ -10,6 +11,7 @@ use crate::config::{KeepAlive, ServiceConfig};
use crate::error::Error;
use crate::h1::{Codec, ExpectHandler, H1Service, UpgradeHandler};
use crate::h2::H2Service;
use crate::helpers::{Data, DataFactory};
use crate::request::Request;
use crate::response::Response;
use crate::service::HttpService;
@ -24,6 +26,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
client_disconnect: u64,
expect: X,
upgrade: Option<U>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, S)>,
}
@ -41,6 +44,7 @@ where
client_disconnect: 0,
expect: ExpectHandler,
upgrade: None,
on_connect: None,
_t: PhantomData,
}
}
@ -115,6 +119,7 @@ where
client_disconnect: self.client_disconnect,
expect: expect.into_new_service(),
upgrade: self.upgrade,
on_connect: self.on_connect,
_t: PhantomData,
}
}
@ -140,10 +145,24 @@ where
client_disconnect: self.client_disconnect,
expect: self.expect,
upgrade: Some(upgrade.into_new_service()),
on_connect: self.on_connect,
_t: PhantomData,
}
}
/// Set on-connect callback.
///
/// It get called once per connection and result of the call
/// get stored to the request's extensions.
pub fn on_connect<F, I>(mut self, f: F) -> Self
where
F: Fn(&T) -> I + 'static,
I: Clone + 'static,
{
self.on_connect = Some(Rc::new(move |io| Box::new(Data(f(io)))));
self
}
/// Finish service configuration and create *http service* for HTTP/1 protocol.
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
where
@ -161,6 +180,7 @@ where
H1Service::with_config(cfg, service.into_new_service())
.expect(self.expect)
.upgrade(self.upgrade)
.on_connect(self.on_connect)
}
/// Finish service configuration and create *http service* for HTTP/2 protocol.
@ -199,5 +219,6 @@ where
HttpService::with_config(cfg, service.into_new_service())
.expect(self.expect)
.upgrade(self.upgrade)
.on_connect(self.on_connect)
}
}

View File

@ -94,7 +94,8 @@ where
T: AsyncRead + AsyncWrite + 'static,
{
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 {
match self.io {
@ -129,7 +130,7 @@ where
type TunnelFuture = Either<
Box<
Future<
dyn Future<
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
Error = SendRequestError,
>,
@ -169,7 +170,8 @@ where
B: AsyncRead + AsyncWrite + 'static,
{
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 {
match self {
@ -190,7 +192,7 @@ where
}
type TunnelFuture = Box<
Future<
dyn Future<
Item = (ResponseHead, Framed<Self::Io, ClientCodec>),
Error = SendRequestError,
>,

View File

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

View File

@ -427,7 +427,9 @@ where
fn check_availibility(&self) {
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> {
match *self {
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::signed::KEY_LEN as SIGNED_KEY_LEN;
static HKDF_DIGEST: &'static Algorithm = &SHA256;
const KEYS_INFO: &'static str = "COOKIE;SIGNED:HMAC-SHA256;PRIVATE:AEAD-AES-256-GCM";
static HKDF_DIGEST: &Algorithm = &SHA256;
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.
///

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
// 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;
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
// 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;
pub const KEY_LEN: usize = 32;

View File

@ -33,6 +33,7 @@ impl<B: MessageBody> Encoder<B> {
) -> ResponseBody<Encoder<B>> {
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|| head.status == StatusCode::NO_CONTENT
|| encoding == ContentEncoding::Identity
|| encoding == ContentEncoding::Auto);

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
/// `ResponseError` reference from it.
pub struct Error {
cause: Box<ResponseError>,
cause: Box<dyn ResponseError>,
}
impl Error {
/// 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()
}
}

View File

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

View File

@ -502,15 +502,15 @@ impl ChunkedState {
fn read_size(rdr: &mut BytesMut, size: &mut u64) -> Poll<ChunkedState, io::Error> {
let radix = 16;
match byte!(rdr) {
b @ b'0'...b'9' => {
b @ b'0'..=b'9' => {
*size *= radix;
*size += u64::from(b - b'0');
}
b @ b'a'...b'f' => {
b @ b'a'..=b'f' => {
*size *= radix;
*size += u64::from(b + 10 - b'a');
}
b @ b'A'...b'F' => {
b @ b'A'..=b'F' => {
*size *= radix;
*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_server_config::IoStream;
use actix_service::Service;
use actix_utils::cloneable::CloneableService;
use bitflags::bitflags;
use bytes::{BufMut, BytesMut};
use futures::{Async, Future, Poll};
@ -13,9 +12,12 @@ use log::{error, trace};
use tokio_timer::Delay;
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService;
use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error};
use crate::error::{ParseError, PayloadError};
use crate::helpers::DataFactory;
use crate::httpmessage::HttpMessage;
use crate::request::Request;
use crate::response::Response;
@ -81,6 +83,7 @@ where
service: CloneableService<S>,
expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>,
on_connect: Option<Box<dyn DataFactory>>,
flags: Flags,
peer_addr: Option<net::SocketAddr>,
error: Option<DispatchError>,
@ -174,12 +177,13 @@ where
U::Error: fmt::Display,
{
/// Create http/1 dispatcher.
pub fn new(
pub(crate) fn new(
stream: T,
config: ServiceConfig,
service: CloneableService<S>,
expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>,
on_connect: Option<Box<dyn DataFactory>>,
) -> Self {
Dispatcher::with_timeout(
stream,
@ -190,11 +194,12 @@ where
service,
expect,
upgrade,
on_connect,
)
}
/// Create http/1 dispatcher with slow request timeout.
pub fn with_timeout(
pub(crate) fn with_timeout(
io: T,
codec: Codec,
config: ServiceConfig,
@ -203,6 +208,7 @@ where
service: CloneableService<S>,
expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>,
on_connect: Option<Box<dyn DataFactory>>,
) -> Self {
let keepalive = config.keep_alive_enabled();
let flags = if keepalive {
@ -234,6 +240,7 @@ where
service,
expect,
upgrade,
on_connect,
flags,
ka_expire,
ka_timer,
@ -495,6 +502,11 @@ where
let pl = self.codec.message_type();
req.head_mut().peer_addr = self.peer_addr;
// on_connect data
if let Some(ref on_connect) = self.on_connect {
on_connect.set(&mut req.extensions_mut());
}
if pl == MessageType::Stream && self.upgrade.is_some() {
self.messages.push_back(DispatcherMessage::Upgrade(req));
break;
@ -693,7 +705,8 @@ where
}
} else {
// read socket into a buf
let should_disconnect = if !inner.flags.contains(Flags::READ_DISCONNECT) {
let should_disconnect =
if !inner.flags.contains(Flags::READ_DISCONNECT) {
read_available(&mut inner.io, &mut inner.read_buf)?
} else {
None
@ -850,6 +863,7 @@ mod tests {
),
CloneableService::new(ExpectHandler),
None,
None,
);
assert!(h1.poll().is_err());

View File

@ -1,16 +1,18 @@
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use actix_codec::Framed;
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
use actix_service::{IntoNewService, NewService, Service};
use actix_utils::cloneable::CloneableService;
use futures::future::{ok, FutureResult};
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
use crate::body::MessageBody;
use crate::cloneable::CloneableService;
use crate::config::{KeepAlive, ServiceConfig};
use crate::error::{DispatchError, Error, ParseError};
use crate::helpers::DataFactory;
use crate::request::Request;
use crate::response::Response;
@ -24,6 +26,7 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
cfg: ServiceConfig,
expect: X,
upgrade: Option<U>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>,
}
@ -44,6 +47,7 @@ where
srv: service.into_new_service(),
expect: ExpectHandler,
upgrade: None,
on_connect: None,
_t: PhantomData,
}
}
@ -55,6 +59,7 @@ where
srv: service.into_new_service(),
expect: ExpectHandler,
upgrade: None,
on_connect: None,
_t: PhantomData,
}
}
@ -79,6 +84,7 @@ where
cfg: self.cfg,
srv: self.srv,
upgrade: self.upgrade,
on_connect: self.on_connect,
_t: PhantomData,
}
}
@ -94,9 +100,19 @@ where
cfg: self.cfg,
srv: self.srv,
expect: self.expect,
on_connect: self.on_connect,
_t: PhantomData,
}
}
/// Set on connect callback.
pub(crate) fn on_connect(
mut self,
f: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> Self {
self.on_connect = f;
self
}
}
impl<T, P, S, B, X, U> NewService for H1Service<T, P, S, B, X, U>
@ -133,6 +149,7 @@ where
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
expect: None,
upgrade: None,
on_connect: self.on_connect.clone(),
cfg: Some(self.cfg.clone()),
_t: PhantomData,
}
@ -157,6 +174,7 @@ where
fut_upg: Option<U::Future>,
expect: Option<X::Service>,
upgrade: Option<U::Service>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: Option<ServiceConfig>,
_t: PhantomData<(T, P, B)>,
}
@ -205,6 +223,7 @@ where
service,
self.expect.take().unwrap(),
self.upgrade.take(),
self.on_connect.clone(),
)))
}
}
@ -214,6 +233,7 @@ pub struct H1ServiceHandler<T, P, S, B, X, U> {
srv: CloneableService<S>,
expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: ServiceConfig,
_t: PhantomData<(T, P, B)>,
}
@ -234,12 +254,14 @@ where
srv: S,
expect: X,
upgrade: Option<U>,
on_connect: Option<Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> H1ServiceHandler<T, P, S, B, X, U> {
H1ServiceHandler {
srv: CloneableService::new(srv),
expect: CloneableService::new(expect),
upgrade: upgrade.map(|s| CloneableService::new(s)),
upgrade: upgrade.map(CloneableService::new),
cfg,
on_connect,
_t: PhantomData,
}
}
@ -292,12 +314,21 @@ where
}
fn call(&mut self, req: Self::Request) -> Self::Future {
let io = req.into_parts().0;
let on_connect = if let Some(ref on_connect) = self.on_connect {
Some(on_connect(&io))
} else {
None
};
Dispatcher::new(
req.into_parts().0,
io,
self.cfg.clone(),
self.srv.clone(),
self.expect.clone(),
self.upgrade.clone(),
on_connect,
)
}
}

View File

@ -6,7 +6,6 @@ use std::{fmt, mem, net};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_server_config::IoStream;
use actix_service::Service;
use actix_utils::cloneable::CloneableService;
use bitflags::bitflags;
use bytes::{Bytes, BytesMut};
use futures::{try_ready, Async, Future, Poll, Sink, Stream};
@ -20,8 +19,10 @@ use log::{debug, error, trace};
use tokio_timer::Delay;
use crate::body::{Body, BodySize, MessageBody, ResponseBody};
use crate::cloneable::CloneableService;
use crate::config::ServiceConfig;
use crate::error::{DispatchError, Error, ParseError, PayloadError, ResponseError};
use crate::helpers::DataFactory;
use crate::message::ResponseHead;
use crate::payload::Payload;
use crate::request::Request;
@ -33,6 +34,7 @@ const CHUNK_SIZE: usize = 16_384;
pub struct Dispatcher<T: IoStream, S: Service<Request = Request>, B: MessageBody> {
service: CloneableService<S>,
connection: Connection<T, Bytes>,
on_connect: Option<Box<dyn DataFactory>>,
config: ServiceConfig,
peer_addr: Option<net::SocketAddr>,
ka_expire: Instant,
@ -49,9 +51,10 @@ where
S::Response: Into<Response<B>>,
B: MessageBody + 'static,
{
pub fn new(
pub(crate) fn new(
service: CloneableService<S>,
connection: Connection<T, Bytes>,
on_connect: Option<Box<dyn DataFactory>>,
config: ServiceConfig,
timeout: Option<Delay>,
peer_addr: Option<net::SocketAddr>,
@ -77,6 +80,7 @@ where
config,
peer_addr,
connection,
on_connect,
ka_expire,
ka_timer,
_t: PhantomData,

View File

@ -1,11 +1,10 @@
use std::fmt::Debug;
use std::marker::PhantomData;
use std::{io, net};
use std::{io, net, rc};
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_server_config::{Io, IoStream, ServerConfig as SrvConfig};
use actix_service::{IntoNewService, NewService, Service};
use actix_utils::cloneable::CloneableService;
use bytes::Bytes;
use futures::future::{ok, FutureResult};
use futures::{try_ready, Async, Future, IntoFuture, Poll, Stream};
@ -14,8 +13,10 @@ use h2::RecvStream;
use log::error;
use crate::body::MessageBody;
use crate::cloneable::CloneableService;
use crate::config::{KeepAlive, ServiceConfig};
use crate::error::{DispatchError, Error, ParseError, ResponseError};
use crate::helpers::DataFactory;
use crate::payload::Payload;
use crate::request::Request;
use crate::response::Response;
@ -26,6 +27,7 @@ use super::dispatcher::Dispatcher;
pub struct H2Service<T, P, S, B> {
srv: S,
cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>,
}
@ -43,6 +45,7 @@ where
H2Service {
cfg,
on_connect: None,
srv: service.into_new_service(),
_t: PhantomData,
}
@ -52,10 +55,20 @@ where
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
H2Service {
cfg,
on_connect: None,
srv: service.into_new_service(),
_t: PhantomData,
}
}
/// Set on connect callback.
pub(crate) fn on_connect(
mut self,
f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> Self {
self.on_connect = f;
self
}
}
impl<T, P, S, B> NewService for H2Service<T, P, S, B>
@ -79,6 +92,7 @@ where
H2ServiceResponse {
fut: self.srv.new_service(cfg).into_future(),
cfg: Some(self.cfg.clone()),
on_connect: self.on_connect.clone(),
_t: PhantomData,
}
}
@ -88,6 +102,7 @@ where
pub struct H2ServiceResponse<T, P, S: NewService, B> {
fut: <S::Future as IntoFuture>::Future,
cfg: Option<ServiceConfig>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>,
}
@ -107,6 +122,7 @@ where
let service = try_ready!(self.fut.poll());
Ok(Async::Ready(H2ServiceHandler::new(
self.cfg.take().unwrap(),
self.on_connect.clone(),
service,
)))
}
@ -116,6 +132,7 @@ where
pub struct H2ServiceHandler<T, P, S, B> {
srv: CloneableService<S>,
cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>,
}
@ -127,9 +144,14 @@ where
S::Response: Into<Response<B>>,
B: MessageBody + 'static,
{
fn new(cfg: ServiceConfig, srv: S) -> H2ServiceHandler<T, P, S, B> {
fn new(
cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
srv: S,
) -> H2ServiceHandler<T, P, S, B> {
H2ServiceHandler {
cfg,
on_connect,
srv: CloneableService::new(srv),
_t: PhantomData,
}
@ -161,11 +183,18 @@ where
fn call(&mut self, req: Self::Request) -> Self::Future {
let io = req.into_parts().0;
let peer_addr = io.peer_addr();
let on_connect = if let Some(ref on_connect) = self.on_connect {
Some(on_connect(&io))
} else {
None
};
H2ServiceHandlerResponse {
state: State::Handshake(
Some(self.srv.clone()),
Some(self.cfg.clone()),
peer_addr,
on_connect,
server::handshake(io),
),
}
@ -181,6 +210,7 @@ where
Option<CloneableService<S>>,
Option<ServiceConfig>,
Option<net::SocketAddr>,
Option<Box<dyn DataFactory>>,
Handshake<T, Bytes>,
),
}
@ -216,15 +246,17 @@ where
ref mut srv,
ref mut config,
ref peer_addr,
ref mut on_connect,
ref mut handshake,
) => match handshake.poll() {
Ok(Async::Ready(conn)) => {
self.state = State::Incoming(Dispatcher::new(
srv.take().unwrap(),
conn,
on_connect.take(),
config.take().unwrap(),
None,
peer_addr.clone(),
*peer_addr,
));
self.poll()
}

View File

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

View File

@ -3,6 +3,8 @@ use std::{io, mem, ptr, slice};
use bytes::{BufMut, BytesMut};
use http::Version;
use crate::extensions::Extensions;
const DEC_DIGITS_LUT: &[u8] = b"0001020304050607080910111213141516171819\
2021222324252627282930313233343536373839\
4041424344454647484950515253545556575859\
@ -180,6 +182,18 @@ impl<'a> io::Write for Writer<'a> {
}
}
pub(crate) trait DataFactory {
fn set(&self, ext: &mut Extensions);
}
pub(crate) struct Data<T>(pub(crate) T);
impl<T: Clone + 'static> DataFactory for Data<T> {
fn set(&self, ext: &mut Extensions) {
ext.insert(self.0.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@ -61,6 +61,7 @@ impl Response {
STATIC_RESP!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
STATIC_RESP!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
STATIC_RESP!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
STATIC_RESP!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
STATIC_RESP!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
STATIC_RESP!(NotImplemented, StatusCode::NOT_IMPLEMENTED);

View File

@ -1,9 +1,7 @@
use std::cell::{Ref, RefMut};
use std::str;
use encoding::all::UTF_8;
use encoding::label::encoding_from_whatwg_label;
use encoding::EncodingRef;
use encoding_rs::{Encoding, UTF_8};
use http::header;
use mime::Mime;
@ -59,10 +57,12 @@ pub trait HttpMessage: Sized {
/// Get content type encoding
///
/// UTF-8 is used by default, If request charset is not set.
fn encoding(&self) -> Result<EncodingRef, ContentTypeError> {
fn encoding(&self) -> Result<&'static Encoding, ContentTypeError> {
if let Some(mime_type) = self.mime_type()? {
if let Some(charset) = mime_type.get_param("charset") {
if let Some(enc) = encoding_from_whatwg_label(charset.as_str()) {
if let Some(enc) =
Encoding::for_label_no_replacement(charset.as_str().as_bytes())
{
Ok(enc)
} else {
Err(ContentTypeError::UnknownEncoding)
@ -166,8 +166,7 @@ where
#[cfg(test)]
mod tests {
use bytes::Bytes;
use encoding::all::ISO_8859_2;
use encoding::Encoding;
use encoding_rs::ISO_8859_2;
use mime;
use super::*;
@ -223,7 +222,7 @@ mod tests {
"application/json; charset=ISO-8859-2",
)
.finish();
assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name());
assert_eq!(ISO_8859_2, req.encoding().unwrap());
}
#[test]

View File

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

View File

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

View File

@ -1,20 +1,21 @@
use std::marker::PhantomData;
use std::{fmt, io, net};
use std::{fmt, io, net, rc};
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_server_config::{
Io as ServerIo, IoStream, Protocol, ServerConfig as SrvConfig,
};
use actix_service::{IntoNewService, NewService, Service};
use actix_utils::cloneable::CloneableService;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use futures::{try_ready, Async, Future, IntoFuture, Poll};
use h2::server::{self, Handshake};
use crate::body::MessageBody;
use crate::builder::HttpServiceBuilder;
use crate::cloneable::CloneableService;
use crate::config::{KeepAlive, ServiceConfig};
use crate::error::{DispatchError, Error};
use crate::helpers::DataFactory;
use crate::request::Request;
use crate::response::Response;
use crate::{h1, h2::Dispatcher};
@ -25,6 +26,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
cfg: ServiceConfig,
expect: X,
upgrade: Option<U>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B)>,
}
@ -61,6 +63,7 @@ where
srv: service.into_new_service(),
expect: h1::ExpectHandler,
upgrade: None,
on_connect: None,
_t: PhantomData,
}
}
@ -75,6 +78,7 @@ where
srv: service.into_new_service(),
expect: h1::ExpectHandler,
upgrade: None,
on_connect: None,
_t: PhantomData,
}
}
@ -104,6 +108,7 @@ where
cfg: self.cfg,
srv: self.srv,
upgrade: self.upgrade,
on_connect: self.on_connect,
_t: PhantomData,
}
}
@ -127,9 +132,19 @@ where
cfg: self.cfg,
srv: self.srv,
expect: self.expect,
on_connect: self.on_connect,
_t: PhantomData,
}
}
/// Set on connect callback.
pub(crate) fn on_connect(
mut self,
f: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> Self {
self.on_connect = f;
self
}
}
impl<T, P, S, B, X, U> NewService for HttpService<T, P, S, B, X, U>
@ -167,6 +182,7 @@ where
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
expect: None,
upgrade: None,
on_connect: self.on_connect.clone(),
cfg: Some(self.cfg.clone()),
_t: PhantomData,
}
@ -180,6 +196,7 @@ pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewServ
fut_upg: Option<U::Future>,
expect: Option<X::Service>,
upgrade: Option<U::Service>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
cfg: Option<ServiceConfig>,
_t: PhantomData<(T, P, B)>,
}
@ -229,6 +246,7 @@ where
service,
self.expect.take().unwrap(),
self.upgrade.take(),
self.on_connect.clone(),
)))
}
}
@ -239,6 +257,7 @@ pub struct HttpServiceHandler<T, P, S, B, X, U> {
expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>,
cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
_t: PhantomData<(T, P, B, X)>,
}
@ -259,12 +278,14 @@ where
srv: S,
expect: X,
upgrade: Option<U>,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,
) -> HttpServiceHandler<T, P, S, B, X, U> {
HttpServiceHandler {
cfg,
on_connect,
srv: CloneableService::new(srv),
expect: CloneableService::new(expect),
upgrade: upgrade.map(|s| CloneableService::new(s)),
upgrade: upgrade.map(CloneableService::new),
_t: PhantomData,
}
}
@ -319,6 +340,13 @@ where
fn call(&mut self, req: Self::Request) -> Self::Future {
let (io, _, proto) = req.into_parts();
let on_connect = if let Some(ref on_connect) = self.on_connect {
Some(on_connect(&io))
} else {
None
};
match proto {
Protocol::Http2 => {
let peer_addr = io.peer_addr();
@ -332,6 +360,7 @@ where
self.cfg.clone(),
self.srv.clone(),
peer_addr,
on_connect,
))),
}
}
@ -342,6 +371,7 @@ where
self.srv.clone(),
self.expect.clone(),
self.upgrade.clone(),
on_connect,
)),
},
_ => HttpServiceHandlerResponse {
@ -352,6 +382,7 @@ where
self.srv.clone(),
self.expect.clone(),
self.upgrade.clone(),
on_connect,
))),
},
}
@ -380,6 +411,7 @@ where
CloneableService<S>,
CloneableService<X>,
Option<CloneableService<U>>,
Option<Box<dyn DataFactory>>,
)>,
),
Handshake(
@ -388,6 +420,7 @@ where
ServiceConfig,
CloneableService<S>,
Option<net::SocketAddr>,
Option<Box<dyn DataFactory>>,
)>,
),
}
@ -448,7 +481,8 @@ where
} else {
panic!()
}
let (io, buf, cfg, srv, expect, upgrade) = data.take().unwrap();
let (io, buf, cfg, srv, expect, upgrade, on_connect) =
data.take().unwrap();
if buf[..14] == HTTP2_PREFACE[..] {
let peer_addr = io.peer_addr();
let io = Io {
@ -460,6 +494,7 @@ where
cfg,
srv,
peer_addr,
on_connect,
)));
} else {
self.state = State::H1(h1::Dispatcher::with_timeout(
@ -471,6 +506,7 @@ where
srv,
expect,
upgrade,
on_connect,
))
}
self.poll()
@ -488,8 +524,10 @@ where
} else {
panic!()
};
let (_, cfg, srv, peer_addr) = data.take().unwrap();
self.state = State::H2(Dispatcher::new(srv, conn, cfg, None, peer_addr));
let (_, cfg, srv, peer_addr, on_connect) = data.take().unwrap();
self.state = State::H2(Dispatcher::new(
srv, conn, on_connect, cfg, None, peer_addr,
));
self.poll()
}
}

View File

@ -37,7 +37,7 @@ pub enum Frame {
Close(Option<CloseReason>),
}
#[derive(Debug)]
#[derive(Debug, Copy, Clone)]
/// WebSockets protocol codec
pub struct Codec {
max_size: usize,

View File

@ -47,10 +47,7 @@ impl Into<u8> for OpCode {
Ping => 9,
Pong => 10,
Bad => {
debug_assert!(
false,
"Attempted to convert invalid opcode to u8. This is a bug."
);
log::error!("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
}
}
@ -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
pub fn hash_key(key: &[u8]) -> String {

View File

@ -0,0 +1,5 @@
# Changes
## [0.1.0] - 2019-06-xx
* Move identity middleware to separate crate

30
actix-identity/Cargo.toml Normal file
View File

@ -0,0 +1,30 @@
[package]
name = "actix-identity"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Identity service for actix web framework."
readme = "README.md"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-identity/"
license = "MIT/Apache-2.0"
edition = "2018"
workspace = ".."
[lib]
name = "actix_identity"
path = "src/lib.rs"
[dependencies]
actix-web = { version = "1.0.0", default-features = false, features = ["secure-cookies"] }
actix-service = "0.4.0"
futures = "0.1.25"
serde = "1.0"
serde_json = "1.0"
time = "0.1.42"
[dev-dependencies]
actix-rt = "0.2.2"
actix-http = "0.2.3"
bytes = "0.4"

View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-identity/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

9
actix-identity/README.md Normal file
View File

@ -0,0 +1,9 @@
# Identity service for actix web framework [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-identity)](https://crates.io/crates/actix-identity) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Documentation & community resources
* [User Guide](https://actix.rs/docs/)
* [API Documentation](https://docs.rs/actix-identity/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
* Minimum supported Rust version: 1.34 or later

View File

@ -10,12 +10,11 @@
//! uses cookies as identity storage.
//!
//! To access current request identity
//! [**Identity**](trait.Identity.html) extractor should be used.
//! [**Identity**](struct.Identity.html) extractor should be used.
//!
//! ```rust
//! use actix_web::middleware::identity::Identity;
//! use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
//! use actix_web::*;
//! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
//!
//! fn index(id: Identity) -> String {
//! // access request identity
@ -39,7 +38,7 @@
//! fn main() {
//! let app = App::new().wrap(IdentityService::new(
//! // <- create identity middleware
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie identity policy
//! .name("auth-cookie")
//! .secure(false)))
//! .service(web::resource("/index.html").to(index))
@ -57,17 +56,17 @@ use futures::{Future, IntoFuture, Poll};
use serde::{Deserialize, Serialize};
use time::Duration;
use crate::cookie::{Cookie, CookieJar, Key, SameSite};
use crate::error::{Error, Result};
use crate::http::header::{self, HeaderValue};
use crate::service::{ServiceRequest, ServiceResponse};
use crate::{dev::Payload, FromRequest, HttpMessage, HttpRequest};
use actix_web::cookie::{Cookie, CookieJar, Key, SameSite};
use actix_web::dev::{Extensions, Payload, ServiceRequest, ServiceResponse};
use actix_web::error::{Error, Result};
use actix_web::http::header::{self, HeaderValue};
use actix_web::{FromRequest, HttpMessage, HttpRequest};
/// The extractor type to obtain your identity from a request.
///
/// ```rust
/// use actix_web::*;
/// use actix_web::middleware::identity::Identity;
/// use actix_identity::Identity;
///
/// fn index(id: Identity) -> Result<String> {
/// // access request identity
@ -96,11 +95,7 @@ impl Identity {
/// Return the claimed identity of the user associated request or
/// ``None`` if no identity can be found associated with the request.
pub fn identity(&self) -> Option<String> {
if let Some(id) = self.0.extensions().get::<IdentityItem>() {
id.id.clone()
} else {
None
}
Identity::get_identity(&self.0.extensions())
}
/// Remember identity.
@ -119,6 +114,14 @@ impl Identity {
id.changed = true;
}
}
fn get_identity(extensions: &Extensions) -> Option<String> {
if let Some(id) = extensions.get::<IdentityItem>() {
id.id.clone()
} else {
None
}
}
}
struct IdentityItem {
@ -126,11 +129,28 @@ struct IdentityItem {
changed: bool,
}
/// Helper trait that allows to get Identity.
///
/// It could be used in middleware but identity policy must be set before any other middleware that needs identity
/// RequestIdentity is implemented both for `ServiceRequest` and `HttpRequest`.
pub trait RequestIdentity {
fn get_identity(&self) -> Option<String>;
}
impl<T> RequestIdentity for T
where
T: HttpMessage,
{
fn get_identity(&self) -> Option<String> {
Identity::get_identity(&self.extensions())
}
}
/// Extractor implementation for Identity type.
///
/// ```rust
/// # use actix_web::*;
/// use actix_web::middleware::identity::Identity;
/// use actix_identity::Identity;
///
/// fn index(id: Identity) -> String {
/// // access request identity
@ -177,7 +197,7 @@ pub trait IdentityPolicy: Sized + 'static {
///
/// ```rust
/// use actix_web::App;
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
///
/// fn main() {
/// let app = App::new().wrap(IdentityService::new(
@ -241,7 +261,7 @@ where
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
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> {
self.service.borrow_mut().poll_ready()
@ -263,7 +283,7 @@ where
res.request().extensions_mut().remove::<IdentityItem>();
if let Some(id) = id {
return Either::A(
Either::A(
backend
.to_response(id.id, id.changed, &mut res)
.into_future()
@ -271,7 +291,7 @@ where
Ok(_) => Ok(res),
Err(e) => Ok(res.error_response(e)),
}),
);
)
} else {
Either::B(ok(res))
}
@ -313,8 +333,7 @@ struct CookieIdentityExtention {
impl CookieIdentityInner {
fn new(key: &[u8]) -> CookieIdentityInner {
let key_v2: Vec<u8> =
key.iter().chain([1, 0, 0, 0].iter()).map(|e| *e).collect();
let key_v2: Vec<u8> = key.iter().chain([1, 0, 0, 0].iter()).cloned().collect();
CookieIdentityInner {
key: Key::from_master(key),
key_v2: Key::from_master(&key_v2),
@ -442,9 +461,8 @@ impl CookieIdentityInner {
/// # Example
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
/// use actix_web::App;
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
///
/// fn main() {
/// let app = App::new().wrap(IdentityService::new(
@ -566,13 +584,14 @@ impl IdentityPolicy for CookieIdentityPolicy {
)
} else if self.0.always_update_cookie() && id.is_some() {
let visit_timestamp = SystemTime::now();
let mut login_timestamp = None;
if self.0.requires_oob_data() {
let login_timestamp = if self.0.requires_oob_data() {
let CookieIdentityExtention {
login_timestamp: lt,
} = res.request().extensions_mut().remove().unwrap();
login_timestamp = lt;
}
lt
} else {
None
};
self.0.set_cookie(
res,
Some(CookieValue {
@ -590,13 +609,13 @@ impl IdentityPolicy for CookieIdentityPolicy {
#[cfg(test)]
mod tests {
use super::*;
use crate::http::StatusCode;
use crate::test::{self, TestRequest};
use crate::{web, App, HttpResponse};
use std::borrow::Borrow;
use super::*;
use actix_web::http::StatusCode;
use actix_web::test::{self, TestRequest};
use actix_web::{web, App, Error, HttpResponse};
const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
const COOKIE_NAME: &'static str = "actix_auth";
const COOKIE_LOGIN: &'static str = "test";
@ -717,8 +736,8 @@ mod tests {
f: F,
) -> impl actix_service::Service<
Request = actix_http::Request,
Response = ServiceResponse<actix_http::body::Body>,
Error = actix_http::Error,
Response = ServiceResponse<actix_web::body::Body>,
Error = Error,
> {
test::init_service(
App::new()

View File

@ -1,5 +1,9 @@
# Changes
## [0.1.3] - 2019-06-06
* Fix ring dependency from actix-web default features for #741.
## [0.1.2] - 2019-06-02
* Fix boundary parsing #876

View File

@ -1,6 +1,6 @@
[package]
name = "actix-multipart"
version = "0.1.2"
version = "0.1.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Multipart support for actix web framework."
readme = "README.md"
@ -18,10 +18,10 @@ name = "actix_multipart"
path = "src/lib.rs"
[dependencies]
actix-web = "1.0.0-rc"
actix-service = "0.4.0"
actix-web = { version = "1.0.0", default-features = false }
actix-service = "0.4.1"
bytes = "0.4"
derive_more = "0.14"
derive_more = "0.15.0"
httparse = "1.3"
futures = "0.1.25"
log = "0.4"
@ -31,4 +31,4 @@ twoway = "0.2"
[dev-dependencies]
actix-rt = "0.2.2"
actix-http = "0.2.2"
actix-http = "0.2.4"

View File

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

View File

@ -418,7 +418,7 @@ impl Stream for Field {
inner.poll(&self.safety)
} else if !self.safety.is_clean() {
return Err(MultipartError::NotConsumed);
Err(MultipartError::NotConsumed)
} else {
Ok(Async::NotReady)
}
@ -533,14 +533,12 @@ impl InnerField {
let b_size = boundary.len() + b_len;
if len < b_size {
return Ok(Async::NotReady);
} else {
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
} else if &payload.buf[b_len..b_size] == boundary.as_bytes() {
// found boundary
return Ok(Async::Ready(None));
}
}
}
}
loop {
return if let Some(idx) = twoway::find_bytes(&payload.buf[pos..], b"\r") {
@ -557,7 +555,7 @@ impl InnerField {
// check boundary
if (&payload.buf[cur..cur + 2] == b"\r\n"
&& &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"--")
{
if cur != 0 {

View File

@ -1,5 +1,12 @@
# Changes
## [0.2.0] - 2019-07-08
* Enhanced ``actix-session`` to facilitate state changes. Use ``Session.renew()``
at successful login to cycle a session (new key/cookie but keeps state).
Use ``Session.purge()`` at logout to invalid a session cookie (and remove
from redis cache, if applicable).
## [0.1.1] - 2019-06-03
* Fix optional cookie session support

View File

@ -1,6 +1,6 @@
[package]
name = "actix-session"
version = "0.1.1"
version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Session for actix web framework."
readme = "README.md"
@ -24,12 +24,12 @@ default = ["cookie-session"]
cookie-session = ["actix-web/secure-cookies"]
[dependencies]
actix-web = "1.0.0-rc"
actix-service = "0.4.0"
actix-web = "1.0.0"
actix-service = "0.4.1"
bytes = "0.4"
derive_more = "0.14"
derive_more = "0.15.0"
futures = "0.1.25"
hashbrown = "0.3.0"
hashbrown = "0.5.0"
serde = "1.0"
serde_json = "1.0"
time = "0.1.42"

View File

@ -6,4 +6,4 @@
* [API Documentation](https://docs.rs/actix-session/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-session](https://crates.io/crates/actix-session)
* Minimum supported Rust version: 1.33 or later
* Minimum supported Rust version: 1.34 or later

View File

@ -28,7 +28,7 @@ use futures::future::{ok, Future, FutureResult};
use futures::Poll;
use serde_json::error::Error as JsonError;
use crate::Session;
use crate::{Session, SessionStatus};
/// Errors that can occur during handling cookie session
#[derive(Debug, From, Display)]
@ -119,7 +119,20 @@ impl CookieSessionInner {
Ok(())
}
fn load(&self, req: &ServiceRequest) -> HashMap<String, String> {
/// invalidates session cookie
fn remove_cookie<B>(&self, res: &mut ServiceResponse<B>) -> Result<(), Error> {
let mut cookie = Cookie::named(self.name.clone());
cookie.set_value("");
cookie.set_max_age(time::Duration::seconds(0));
cookie.set_expires(time::now() - time::Duration::days(365));
let val = HeaderValue::from_str(&cookie.to_string())?;
res.headers_mut().append(SET_COOKIE, val);
Ok(())
}
fn load(&self, req: &ServiceRequest) -> (bool, HashMap<String, String>) {
if let Ok(cookies) = req.cookies() {
for cookie in cookies.iter() {
if cookie.name() == self.name {
@ -134,13 +147,13 @@ impl CookieSessionInner {
};
if let Some(cookie) = cookie_opt {
if let Ok(val) = serde_json::from_str(cookie.value()) {
return val;
return (false, val);
}
}
}
}
}
HashMap::new()
(true, HashMap::new())
}
}
@ -296,23 +309,44 @@ where
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
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> {
self.service.poll_ready()
}
/// On first request, a new session cookie is returned in response, regardless
/// of whether any session state is set. With subsequent requests, if the
/// session state changes, then set-cookie is returned in response. As
/// a user logs out, call session.purge() to set SessionStatus accordingly
/// and this will trigger removal of the session cookie in the response.
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
let inner = self.inner.clone();
let state = self.inner.load(&req);
let (is_new, state) = self.inner.load(&req);
Session::set_session(state.into_iter(), &mut req);
Box::new(self.service.call(req).map(move |mut res| {
if let Some(state) = Session::get_changes(&mut res) {
match Session::get_changes(&mut res) {
(SessionStatus::Changed, Some(state))
| (SessionStatus::Renewed, Some(state)) => {
res.checked_expr(|res| inner.set_cookie(res, state))
}
(SessionStatus::Unchanged, _) =>
// set a new session cookie upon first request (new client)
{
if is_new {
let state: HashMap<String, String> = HashMap::new();
res.checked_expr(|res| inner.set_cookie(res, state.into_iter()))
} else {
res
}
}
(SessionStatus::Purged, _) => {
let _ = inner.remove_cookie(&mut res);
res
}
_ => res,
}
}))
}
}

View File

@ -98,10 +98,23 @@ impl UserSession for ServiceRequest {
}
}
#[derive(PartialEq, Clone, Debug)]
pub enum SessionStatus {
Changed,
Purged,
Renewed,
Unchanged,
}
impl Default for SessionStatus {
fn default() -> SessionStatus {
SessionStatus::Unchanged
}
}
#[derive(Default)]
struct SessionInner {
state: HashMap<String, String>,
changed: bool,
pub status: SessionStatus,
}
impl Session {
@ -117,26 +130,47 @@ impl Session {
/// Set a `value` from the session.
pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), Error> {
let mut inner = self.0.borrow_mut();
inner.changed = true;
if inner.status != SessionStatus::Purged {
inner.status = SessionStatus::Changed;
inner
.state
.insert(key.to_owned(), serde_json::to_string(&value)?);
}
Ok(())
}
/// Remove value from the session.
pub fn remove(&self, key: &str) {
let mut inner = self.0.borrow_mut();
inner.changed = true;
if inner.status != SessionStatus::Purged {
inner.status = SessionStatus::Changed;
inner.state.remove(key);
}
}
/// Clear the session.
pub fn clear(&self) {
let mut inner = self.0.borrow_mut();
inner.changed = true;
if inner.status != SessionStatus::Purged {
inner.status = SessionStatus::Changed;
inner.state.clear()
}
}
/// Removes session, both client and server side.
pub fn purge(&self) {
let mut inner = self.0.borrow_mut();
inner.status = SessionStatus::Purged;
inner.state.clear();
}
/// Renews the session key, assigning existing session state to new key.
pub fn renew(&self) {
let mut inner = self.0.borrow_mut();
if inner.status != SessionStatus::Purged {
inner.status = SessionStatus::Renewed;
}
}
pub fn set_session(
data: impl Iterator<Item = (String, String)>,
@ -149,7 +183,10 @@ impl Session {
pub fn get_changes<B>(
res: &mut ServiceResponse<B>,
) -> Option<impl Iterator<Item = (String, String)>> {
) -> (
SessionStatus,
Option<impl Iterator<Item = (String, String)>>,
) {
if let Some(s_impl) = res
.request()
.extensions()
@ -157,9 +194,9 @@ impl Session {
{
let state =
std::mem::replace(&mut s_impl.borrow_mut().state, HashMap::new());
Some(state.into_iter())
(s_impl.borrow().status.clone(), Some(state.into_iter()))
} else {
None
(SessionStatus::Unchanged, None)
}
}
@ -224,7 +261,8 @@ mod tests {
session.remove("key");
let mut res = req.into_response(HttpResponse::Ok().finish());
let changes: Vec<_> = Session::get_changes(&mut res).unwrap().collect();
let (_status, state) = Session::get_changes(&mut res);
let changes: Vec<_> = state.unwrap().collect();
assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
}
@ -241,4 +279,22 @@ mod tests {
let res = session.get::<String>("key").unwrap();
assert_eq!(res, Some("value".to_string()));
}
#[test]
fn purge_session() {
let req = test::TestRequest::default().to_srv_request();
let session = Session::get_session(&mut *req.extensions_mut());
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
session.purge();
assert_eq!(session.0.borrow().status, SessionStatus::Purged);
}
#[test]
fn renew_session() {
let req = test::TestRequest::default().to_srv_request();
let session = Session::get_session(&mut *req.extensions_mut());
assert_eq!(session.0.borrow().status, SessionStatus::Unchanged);
session.renew();
assert_eq!(session.0.borrow().status, SessionStatus::Renewed);
}
}

View File

@ -1,5 +1,9 @@
# Changes
## [1.0.1] - 2019-06-28
* Allow to use custom ws codec with `WebsocketContext` #925
## [1.0.0] - 2019-05-29
* Update actix-http and actix-web

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web-actors"
version = "1.0.0"
version = "1.0.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix actors support for actix web framework."
readme = "README.md"
@ -19,8 +19,8 @@ path = "src/lib.rs"
[dependencies]
actix = "0.8.3"
actix-web = "1.0.0-rc"
actix-http = "0.2.2"
actix-web = "1.0.3"
actix-http = "0.2.5"
actix-codec = "0.1.2"
bytes = "0.4"
futures = "0.1.25"

View File

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

View File

@ -177,9 +177,30 @@ where
inner: ContextParts::new(mb.sender_producer()),
messages: VecDeque::new(),
};
ctx.add_stream(WsStream::new(stream));
ctx.add_stream(WsStream::new(stream, Codec::new()));
WebsocketContextFut::new(ctx, actor, mb)
WebsocketContextFut::new(ctx, actor, mb, Codec::new())
}
#[inline]
/// Create a new Websocket context from a request, an actor, and a codec
pub fn with_codec<S>(
actor: A,
stream: S,
codec: Codec,
) -> impl Stream<Item = Bytes, Error = Error>
where
A: StreamHandler<Message, ProtocolError>,
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
{
let mb = Mailbox::default();
let mut ctx = WebsocketContext {
inner: ContextParts::new(mb.sender_producer()),
messages: VecDeque::new(),
};
ctx.add_stream(WsStream::new(stream, codec));
WebsocketContextFut::new(ctx, actor, mb, codec)
}
/// Create a new Websocket context
@ -197,11 +218,11 @@ where
inner: ContextParts::new(mb.sender_producer()),
messages: VecDeque::new(),
};
ctx.add_stream(WsStream::new(stream));
ctx.add_stream(WsStream::new(stream, Codec::new()));
let act = f(&mut ctx);
WebsocketContextFut::new(ctx, act, mb)
WebsocketContextFut::new(ctx, act, mb, Codec::new())
}
}
@ -288,11 +309,11 @@ impl<A> WebsocketContextFut<A>
where
A: Actor<Context = WebsocketContext<A>>,
{
fn new(ctx: WebsocketContext<A>, act: A, mailbox: Mailbox<A>) -> Self {
fn new(ctx: WebsocketContext<A>, act: A, mailbox: Mailbox<A>, codec: Codec) -> Self {
let fut = ContextFut::new(ctx, act, mailbox);
WebsocketContextFut {
fut,
encoder: Codec::new(),
encoder: codec,
buf: BytesMut::new(),
closed: false,
}
@ -353,10 +374,10 @@ impl<S> WsStream<S>
where
S: Stream<Item = Bytes, Error = PayloadError>,
{
fn new(stream: S) -> Self {
fn new(stream: S, codec: Codec) -> Self {
Self {
stream,
decoder: Codec::new(),
decoder: codec,
buf: BytesMut::new(),
closed: false,
}
@ -414,7 +435,7 @@ where
}
}
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::Pong(s) => Message::Pong(s),

View File

@ -16,7 +16,7 @@ quote = "0.6.12"
syn = { version = "0.15.34", features = ["full", "parsing", "extra-traits"] }
[dev-dependencies]
actix-web = { version = "1.0.0-rc" }
actix-http = { version = "0.2.2", features=["ssl"] }
actix-web = { version = "1.0.0" }
actix-http = { version = "0.2.4", features=["ssl"] }
actix-http-test = { version = "0.2.0", features=["ssl"] }
futures = { version = "0.1" }

View File

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

View File

@ -1,7 +1,7 @@
use actix_http::HttpService;
use actix_http_test::TestServer;
use actix_web::{http, web::Path, App, HttpResponse, Responder};
use actix_web_codegen::{delete, get, post, put, patch, head, connect, options, trace};
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
use futures::{future, Future};
#[get("/test")]

View File

@ -1,5 +1,20 @@
# Changes
## [0.2.2] - 2019-07-01
### Changed
* Always append a colon after username in basic auth
* Upgrade `rand` dependency version to 0.7
## [0.2.1] - 2019-06-05
### Added
* Add license files
## [0.2.0] - 2019-05-12
### Added

View File

@ -1,6 +1,6 @@
[package]
name = "awc"
version = "0.2.0"
version = "0.2.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http client."
readme = "README.md"
@ -40,16 +40,16 @@ flate2-rust = ["actix-http/flate2-rust"]
[dependencies]
actix-codec = "0.1.2"
actix-service = "0.4.0"
actix-http = "0.2.0"
actix-service = "0.4.1"
actix-http = "0.2.4"
base64 = "0.10.1"
bytes = "0.4"
derive_more = "0.14"
derive_more = "0.15.0"
futures = "0.1.25"
log =" 0.4"
mime = "0.3"
percent-encoding = "1.0"
rand = "0.6"
rand = "0.7"
serde = "1.0"
serde_json = "1.0"
serde_urlencoded = "0.5.3"
@ -58,13 +58,13 @@ openssl = { version="0.10", optional = true }
[dev-dependencies]
actix-rt = "0.2.2"
actix-web = { version = "1.0.0-beta.4", features=["ssl"] }
actix-http = { version = "0.2.0", features=["ssl"] }
actix-web = { version = "1.0.0", features=["ssl"] }
actix-http = { version = "0.2.4", features=["ssl"] }
actix-http-test = { version = "0.2.0", features=["ssl"] }
actix-utils = "0.4.0"
actix-server = { version = "0.5.0", features=["ssl"] }
actix-utils = "0.4.1"
actix-server = { version = "0.5.1", features=["ssl"] }
brotli2 = { version="0.3.2" }
flate2 = { version="1.0.2" }
env_logger = "0.6"
rand = "0.6"
rand = "0.7"
tokio-tcp = "0.1"

View File

@ -21,6 +21,12 @@ pub struct ClientBuilder {
max_redirects: usize,
}
impl Default for ClientBuilder {
fn default() -> Self {
Self::new()
}
}
impl ClientBuilder {
pub fn new() -> Self {
ClientBuilder {
@ -115,7 +121,7 @@ impl ClientBuilder {
{
let auth = match password {
Some(password) => format!("{}:{}", username, password),
None => format!("{}", username),
None => format!("{}:", username),
};
self.header(
header::AUTHORIZATION,
@ -164,7 +170,7 @@ mod tests {
.unwrap()
.to_str()
.unwrap(),
"Basic dXNlcm5hbWU="
"Basic dXNlcm5hbWU6"
);
}

View File

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

View File

@ -1,7 +1,8 @@
#![allow(clippy::borrow_interior_mutable_const)]
//! An HTTP Client
//!
//! ```rust
//! # use futures::future::{Future, lazy};
//! use futures::future::{lazy, Future};
//! use actix_rt::System;
//! use awc::Client;
//!
@ -38,6 +39,7 @@ pub mod test;
pub mod ws;
pub use self::builder::ClientBuilder;
pub use self::connect::BoxedSocket;
pub use self::request::ClientRequest;
pub use self::response::{ClientResponse, JsonBody, MessageBody};

View File

@ -185,9 +185,7 @@ impl ClientRequest {
{
match HeaderName::try_from(key) {
Ok(key) => match value.try_into() {
Ok(value) => {
let _ = self.head.headers.append(key, value);
}
Ok(value) => self.head.headers.append(key, value),
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) {
Ok(key) => match value.try_into() {
Ok(value) => {
let _ = self.head.headers.insert(key, value);
}
Ok(value) => self.head.headers.insert(key, value),
Err(e) => self.err = Some(e.into()),
},
Err(e) => self.err = Some(e.into()),
@ -223,9 +219,7 @@ impl ClientRequest {
Ok(key) => {
if !self.head.headers.contains_key(&key) {
match value.try_into() {
Ok(value) => {
let _ = self.head.headers.insert(key, value);
}
Ok(value) => self.head.headers.insert(key, value),
Err(e) => self.err = Some(e.into()),
}
}
@ -257,9 +251,7 @@ impl ClientRequest {
HeaderValue: HttpTryFrom<V>,
{
match HeaderValue::try_from(value) {
Ok(value) => {
let _ = self.head.headers.insert(header::CONTENT_TYPE, value);
}
Ok(value) => self.head.headers.insert(header::CONTENT_TYPE, value),
Err(e) => self.err = Some(e.into()),
}
self
@ -280,7 +272,7 @@ impl ClientRequest {
{
let auth = match password {
Some(password) => format!("{}:{}", username, password),
None => format!("{}", username),
None => format!("{}:", username),
};
self.header(
header::AUTHORIZATION,
@ -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() {
let mut jar = CookieJar::new();
jar.add(cookie.into_owned());
@ -465,7 +457,7 @@ impl ClientRequest {
});
// 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| {
if let Some(e) = e.into_inner() {
e
@ -664,7 +656,7 @@ mod tests {
.unwrap()
.to_str()
.unwrap(),
"Basic dXNlcm5hbWU="
"Basic dXNlcm5hbWU6"
);
}

View File

@ -68,7 +68,7 @@ impl TestResponse {
}
/// 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
}

View File

@ -90,7 +90,7 @@ impl WebsocketsRequest {
}
/// 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() {
let mut jar = CookieJar::new();
jar.add(cookie.into_owned());
@ -195,7 +195,7 @@ impl WebsocketsRequest {
{
let auth = match password {
Some(password) => format!("{}:{}", username, password),
None => format!("{}", username),
None => format!("{}:", username),
};
self.header(AUTHORIZATION, format!("Basic {}", base64::encode(&auth)))
}
@ -443,7 +443,7 @@ mod tests {
.unwrap()
.to_str()
.unwrap(),
"Basic dXNlcm5hbWU="
"Basic dXNlcm5hbWU6"
);
}

View File

@ -8,7 +8,7 @@ use actix_service::boxed::{self, BoxedNewService};
use actix_service::{
apply_transform, IntoNewService, IntoTransform, NewService, Transform,
};
use futures::IntoFuture;
use futures::{Future, IntoFuture};
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
use crate::config::{AppConfig, AppConfigInner, ServiceConfig};
@ -23,15 +23,18 @@ use crate::service::{
};
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type FnDataFactory =
Box<dyn Fn() -> Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>;
/// Application builder - structure that follows the builder pattern
/// for building application instances.
pub struct App<T, B> {
endpoint: T,
services: Vec<Box<ServiceFactory>>,
services: Vec<Box<dyn ServiceFactory>>,
default: Option<Rc<HttpNewService>>,
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
data: Vec<Box<DataFactory>>,
data: Vec<Box<dyn DataFactory>>,
data_factories: Vec<FnDataFactory>,
config: AppConfigInner,
external: Vec<ResourceDef>,
_t: PhantomData<(B)>,
@ -44,6 +47,7 @@ impl App<AppEntry, Body> {
App {
endpoint: AppEntry::new(fref.clone()),
data: Vec::new(),
data_factories: Vec::new(),
services: Vec::new(),
default: None,
factory_ref: fref,
@ -100,6 +104,38 @@ where
self
}
/// Set application data factory. This function is
/// similar to `.data()` but it accepts data factory. Data object get
/// constructed asynchronously during application initialization.
pub fn data_factory<F, Out>(mut self, data: F) -> Self
where
F: Fn() -> Out + 'static,
Out: IntoFuture + 'static,
Out::Error: std::fmt::Debug,
{
self.data_factories.push(Box::new(move || {
Box::new(
data()
.into_future()
.map_err(|e| {
log::error!("Can not construct data instance: {:?}", e);
})
.map(|data| {
let data: Box<dyn DataFactory> = Box::new(Data::new(data));
data
}),
)
}));
self
}
/// Set application data. Application data could be accessed
/// by using `Data<T>` extractor where `T` is data type.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
self.data.push(Box::new(data));
self
}
/// Run external configuration as part of the application building
/// process
///
@ -218,7 +254,6 @@ where
/// It is also possible to use static files as default service.
///
/// ```rust
/// use actix_files::Files;
/// use actix_web::{web, App, HttpResponse};
///
/// fn main() {
@ -226,7 +261,7 @@ where
/// .service(
/// web::resource("/index.html").to(|| HttpResponse::Ok()))
/// .default_service(
/// Files::new("", "./static")
/// web::to(|| HttpResponse::NotFound())
/// );
/// }
/// ```
@ -343,6 +378,7 @@ where
App {
endpoint,
data: self.data,
data_factories: self.data_factories,
services: self.services,
default: self.default,
factory_ref: self.factory_ref,
@ -417,6 +453,7 @@ where
fn into_new_service(self) -> AppInit<T, B> {
AppInit {
data: Rc::new(self.data),
data_factories: Rc::new(self.data_factories),
endpoint: self.endpoint,
services: Rc::new(RefCell::new(self.services)),
external: RefCell::new(self.external),
@ -484,24 +521,24 @@ mod tests {
assert_eq!(resp.status(), StatusCode::CREATED);
}
// #[test]
// fn test_data_factory() {
// let mut srv =
// init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service(
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
// ));
// let req = TestRequest::default().to_request();
// let resp = block_on(srv.call(req)).unwrap();
// assert_eq!(resp.status(), StatusCode::OK);
#[test]
fn test_data_factory() {
let mut srv =
init_service(App::new().data_factory(|| Ok::<_, ()>(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// let mut srv =
// init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service(
// web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
// ));
// let req = TestRequest::default().to_request();
// let resp = block_on(srv.call(req)).unwrap();
// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
// }
let mut srv =
init_service(App::new().data_factory(|| Ok::<_, ()>(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
fn md<S, B>(
req: ServiceRequest,

View File

@ -18,13 +18,15 @@ use crate::request::{HttpRequest, HttpRequestPool};
use crate::rmap::ResourceMap;
use crate::service::{ServiceFactory, ServiceRequest, ServiceResponse};
type Guards = Vec<Box<Guard>>;
type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = Either<
FutureResult<ServiceResponse, Error>,
Box<Future<Item = ServiceResponse, Error = Error>>,
Box<dyn Future<Item = ServiceResponse, Error = Error>>,
>;
type FnDataFactory =
Box<dyn Fn() -> Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>;
/// Service factory to convert `Request` to a `ServiceRequest<S>`.
/// It also executes data factories.
@ -39,9 +41,10 @@ where
>,
{
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) 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) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
pub(crate) external: RefCell<Vec<ResourceDef>>,
@ -119,16 +122,12 @@ where
let rmap = Rc::new(rmap);
rmap.finish(rmap.clone());
// create app data container
let mut data = Extensions::new();
for f in self.data.iter() {
f.create(&mut data);
}
AppInitResult {
endpoint: None,
endpoint_fut: self.endpoint.new_service(&()),
data: Rc::new(data),
data: self.data.clone(),
data_factories: Vec::new(),
data_factories_fut: self.data_factories.iter().map(|f| f()).collect(),
config,
rmap,
_t: PhantomData,
@ -144,7 +143,9 @@ where
endpoint_fut: T::Future,
rmap: Rc<ResourceMap>,
config: AppConfig,
data: Rc<Extensions>,
data: Rc<Vec<Box<dyn DataFactory>>>,
data_factories: Vec<Box<dyn DataFactory>>,
data_factories_fut: Vec<Box<dyn Future<Item = Box<dyn DataFactory>, Error = ()>>>,
_t: PhantomData<B>,
}
@ -159,21 +160,43 @@ where
>,
{
type Item = AppInitService<T::Service, B>;
type Error = T::InitError;
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// async data factories
let mut idx = 0;
while idx < self.data_factories_fut.len() {
match self.data_factories_fut[idx].poll()? {
Async::Ready(f) => {
self.data_factories.push(f);
self.data_factories_fut.remove(idx);
}
Async::NotReady => idx += 1,
}
}
if self.endpoint.is_none() {
if let Async::Ready(srv) = self.endpoint_fut.poll()? {
self.endpoint = Some(srv);
}
}
if self.endpoint.is_some() {
if self.endpoint.is_some() && self.data_factories_fut.is_empty() {
// create app data container
let mut data = Extensions::new();
for f in self.data.iter() {
f.create(&mut data);
}
for f in &self.data_factories {
f.create(&mut data);
}
Ok(Async::Ready(AppInitService {
service: self.endpoint.take().unwrap(),
rmap: self.rmap.clone(),
config: self.config.clone(),
data: self.data.clone(),
data: Rc::new(data),
pool: HttpRequestPool::create(),
}))
} else {
@ -275,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
#[doc(hidden)]
pub struct AppRoutingFactoryResponse {
fut: Vec<CreateAppRoutingItem>,
default: Option<HttpService>,
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
default_fut: Option<Box<dyn Future<Item = HttpService, Error = ()>>>,
}
enum CreateAppRoutingItem {

View File

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

View File

@ -54,7 +54,7 @@ pub(crate) trait DataFactory {
///
/// let app = App::new()
/// // Store `MyData` in application storage.
/// .data(data.clone())
/// .register_data(data.clone())
/// .service(
/// web::resource("/index.html").route(
/// web::get().to(index)));
@ -73,7 +73,7 @@ impl<T> Data<T> {
Data(Arc::new(state))
}
/// Get referecnce to inner app data.
/// Get reference to inner app data.
pub fn get_ref(&self) -> &T {
self.0.as_ref()
}
@ -118,7 +118,7 @@ impl<T: 'static> FromRequest for Data<T> {
impl<T: 'static> DataFactory for Data<T> {
fn create(&self, extensions: &mut Extensions) -> bool {
if !extensions.contains::<Data<T>>() {
let _ = extensions.insert(Data(self.0.clone()));
extensions.insert(Data(self.0.clone()));
true
} else {
false
@ -130,6 +130,7 @@ impl<T: 'static> DataFactory for Data<T> {
mod tests {
use actix_service::Service;
use super::*;
use crate::http::StatusCode;
use crate::test::{block_on, init_service, TestRequest};
use crate::{web, App, HttpResponse};
@ -154,6 +155,26 @@ mod tests {
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn test_register_data_extractor() {
let mut srv =
init_service(App::new().register_data(Data::new(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let mut srv =
init_service(App::new().register_data(Data::new(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn test_route_data_extractor() {
let mut srv =

View File

@ -92,6 +92,23 @@ impl ResponseError for JsonPayloadError {
}
}
/// A set of errors that can occur during parsing request paths
#[derive(Debug, Display, From)]
pub enum PathError {
/// Deserialize error
#[display(fmt = "Path deserialize error: {}", _0)]
Deserialize(de::Error),
}
/// Return `BadRequest` for `PathError`
impl ResponseError for PathError {
fn error_response(&self) -> HttpResponse {
match *self {
PathError::Deserialize(_) => HttpResponse::new(StatusCode::BAD_REQUEST),
}
}
}
/// A set of errors that can occur during parsing query strings
#[derive(Debug, Display, From)]
pub enum QueryPayloadError {

View File

@ -94,7 +94,7 @@ where
{
type Config = T::Config;
type Error = Error;
type Future = Box<Future<Item = Option<T>, Error = Error>>;
type Future = Box<dyn Future<Item = Option<T>, Error = Error>>;
#[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
@ -165,7 +165,7 @@ where
{
type Config = T::Config;
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]
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.
pub struct AnyGuard(Vec<Box<Guard>>);
pub struct AnyGuard(Vec<Box<dyn Guard>>);
impl AnyGuard {
/// 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.
pub struct AllGuard(Vec<Box<Guard>>);
pub struct AllGuard(Vec<Box<dyn Guard>>);
impl AllGuard {
/// 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)]
pub struct NotGuard(Box<Guard>);
pub struct NotGuard(Box<dyn Guard>);
impl Guard for NotGuard {
fn check(&self, request: &RequestHead) -> bool {

View File

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

View File

@ -25,7 +25,7 @@ impl ConnectionInfo {
Ref::map(req.extensions(), |e| e.get().unwrap())
}
#[allow(clippy::cyclomatic_complexity)]
#[allow(clippy::cognitive_complexity)]
fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo {
let mut host = 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
//! for Rust.
//!
@ -66,15 +67,15 @@
//!
//! ## Package feature
//!
//! * `client` - enables http client
//! * `client` - enables http client (default enabled)
//! * `ssl` - enables ssl support via `openssl` crate, supports `http/2`
//! * `rust-tls` - enables ssl support via `rustls` crate, supports `http/2`
//! * `secure-cookies` - enables secure cookies support, includes `ring` crate as
//! dependency
//! * `brotli` - enables `brotli` compression support, requires `c`
//! compiler
//! compiler (default enabled)
//! * `flate2-zlib` - enables `gzip`, `deflate` compression support, requires
//! `c` compiler
//! `c` compiler (default enabled)
//! * `flate2-rust` - experimental rust based implementation for
//! `gzip`, `deflate` compression.
//!
@ -134,6 +135,8 @@ pub mod dev {
//! ```
pub use crate::config::{AppConfig, AppService};
#[doc(hidden)]
pub use crate::handler::{AsyncFactory, Factory};
pub use crate::info::ConnectionInfo;
pub use crate::rmap::ResourceMap;
pub use crate::service::{

View File

@ -119,7 +119,7 @@ where
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
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> {
self.service.poll_ready()

View File

@ -15,10 +15,10 @@ pub enum ErrorHandlerResponse<B> {
/// New http response got generated
Response(ServiceResponse<B>),
/// 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.
///
@ -117,7 +117,7 @@ where
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
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> {
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 => {
*self = FormatText::Str(format!("{}", now.rfc3339()))
*self = FormatText::Str(now.rfc3339().to_string())
}
FormatText::RequestHeader(ref 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> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {

View File

@ -2,7 +2,6 @@
mod compress;
pub use self::compress::{BodyEncoding, Compress};
pub mod cors;
mod defaultheaders;
pub mod errhandlers;
mod logger;
@ -11,6 +10,3 @@ mod normalize;
pub use self::defaultheaders::DefaultHeaders;
pub use self::logger::Logger;
pub use self::normalize::NormalizePath;
#[cfg(feature = "secure-cookies")]
pub mod identity;

View File

@ -174,6 +174,12 @@ impl HttpRequest {
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 address is actual socket address, if proxy is used in front of
@ -186,6 +192,9 @@ impl HttpRequest {
}
/// Get *ConnectionInfo* for the current request.
///
/// This method panics if request's extensions container is already
/// borrowed.
#[inline]
pub fn connection_info(&self) -> Ref<ConnectionInfo> {
ConnectionInfo::get(self.head(), &*self.app_config())

View File

@ -27,7 +27,7 @@ type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error
/// Resource in turn has at least one route.
/// Route consists of an handlers objects and list of guards
/// (objects that implement `Guard` trait).
/// Resources and rouets uses builder-like pattern for configuration.
/// Resources and routes uses builder-like pattern for configuration.
/// During request handling, resource object iterate through all routes
/// and check guards for specific route, if request matches all
/// guards, route considered matched and route handler get called.
@ -50,7 +50,7 @@ pub struct Resource<T = ResourceEndpoint> {
name: Option<String>,
routes: Vec<Route>,
data: Option<Extensions>,
guards: Vec<Box<Guard>>,
guards: Vec<Box<dyn Guard>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
factory_ref: Rc<RefCell<Option<ResourceFactory>>>,
}
@ -118,7 +118,7 @@ where
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
}
@ -245,7 +245,7 @@ where
/// ```rust
/// # use actix_web::*;
/// # 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!()
/// # }
/// App::new().service(web::resource("/").route(web::route().to_async(index)));
@ -426,7 +426,7 @@ where
fn into_new_service(self) -> T {
*self.factory_ref.borrow_mut() = Some(ResourceFactory {
routes: self.routes,
data: self.data.map(|data| Rc::new(data)),
data: self.data.map(Rc::new),
default: self.default,
});
@ -478,7 +478,7 @@ pub struct CreateResourceService {
fut: Vec<CreateRouteServiceItem>,
data: Option<Rc<Extensions>>,
default: Option<HttpService>,
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
default_fut: Option<Box<dyn Future<Item = HttpService, Error = ()>>>,
}
impl Future for CreateResourceService {
@ -542,7 +542,7 @@ impl Service for ResourceService {
type Error = Error;
type Future = Either<
FutureResult<ServiceResponse, Error>,
Box<Future<Item = ServiceResponse, Error = Error>>,
Box<dyn Future<Item = ServiceResponse, Error = Error>>,
>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {

View File

@ -137,6 +137,22 @@ impl Responder for () {
}
}
impl<T> Responder for (T, StatusCode)
where
T: Responder,
{
type Error = T::Error;
type Future = CustomResponderFut<T>;
fn respond_to(self, req: &HttpRequest) -> Self::Future {
CustomResponderFut {
fut: self.0.respond_to(req).into_future(),
status: Some(self.1),
headers: None,
}
}
}
impl Responder for &'static str {
type Error = Error;
type Future = FutureResult<Response, Error>;
@ -321,7 +337,7 @@ impl<T: Responder> Future for CustomResponderFut<T> {
/// use actix_web::{Either, Error, HttpResponse};
///
/// type RegisterResult =
/// Either<HttpResponse, Box<Future<Item = HttpResponse, Error = Error>>>;
/// Either<HttpResponse, Box<dyn Future<Item = HttpResponse, Error = Error>>>;
///
/// fn index() -> RegisterResult {
/// if is_a_variant() {
@ -395,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
I: Responder + 'static,
E: Into<Error> + 'static,
{
type Error = Error;
type Future = Box<Future<Item = Response, Error = Error>>;
type Future = Box<dyn Future<Item = Response, Error = Error>>;
#[inline]
fn respond_to(self, req: &HttpRequest) -> Self::Future {
@ -624,4 +640,28 @@ pub(crate) mod tests {
HeaderValue::from_static("json")
);
}
#[test]
fn test_tuple_responder_with_status_code() {
let req = TestRequest::default().to_http_request();
let res =
block_on(("test".to_string(), StatusCode::BAD_REQUEST).respond_to(&req))
.unwrap();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
assert_eq!(res.body().bin_ref(), b"test");
let req = TestRequest::default().to_http_request();
let res = block_on(
("test".to_string(), StatusCode::OK)
.with_header("content-type", "json")
.respond_to(&req),
)
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.body().bin_ref(), b"test");
assert_eq!(
res.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("json")
);
}
}

View File

@ -38,7 +38,8 @@ impl ResourceMap {
pub(crate) fn finish(&self, current: Rc<ResourceMap>) {
for (_, nested) in &self.patterns {
if let Some(ref nested) = nested {
*nested.parent.borrow_mut() = Some(current.clone())
*nested.parent.borrow_mut() = Some(current.clone());
nested.finish(nested.clone());
}
}
}
@ -122,7 +123,7 @@ impl ResourceMap {
I: AsRef<str>,
{
if let Some(pattern) = self.named.get(name) {
if pattern.pattern().starts_with("/") {
if pattern.pattern().starts_with('/') {
self.fill_root(path, elements)?;
}
if pattern.resource_path(path, elements) {

View File

@ -13,26 +13,26 @@ use crate::service::{ServiceRequest, ServiceResponse};
use crate::HttpResponse;
type BoxedRouteService<Req, Res> = Box<
Service<
dyn Service<
Request = Req,
Response = Res,
Error = Error,
Future = Either<
FutureResult<Res, Error>,
Box<Future<Item = Res, Error = Error>>,
Box<dyn Future<Item = Res, Error = Error>>,
>,
>,
>;
type BoxedRouteNewService<Req, Res> = Box<
NewService<
dyn NewService<
Config = (),
Request = Req,
Response = Res,
Error = Error,
InitError = (),
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.
pub struct Route {
service: BoxedRouteNewService<ServiceRequest, ServiceResponse>,
guards: Rc<Vec<Box<Guard>>>,
guards: Rc<Vec<Box<dyn Guard>>>,
}
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())
}
}
@ -78,12 +78,13 @@ impl NewService for Route {
}
}
type RouteFuture =
Box<Future<Item = BoxedRouteService<ServiceRequest, ServiceResponse>, Error = ()>>;
type RouteFuture = Box<
dyn Future<Item = BoxedRouteService<ServiceRequest, ServiceResponse>, Error = ()>,
>;
pub struct CreateRouteService {
fut: RouteFuture,
guards: Rc<Vec<Box<Guard>>>,
guards: Rc<Vec<Box<dyn Guard>>>,
}
impl Future for CreateRouteService {
@ -103,7 +104,7 @@ impl Future for CreateRouteService {
pub struct RouteService {
service: BoxedRouteService<ServiceRequest, ServiceResponse>,
guards: Rc<Vec<Box<Guard>>>,
guards: Rc<Vec<Box<dyn Guard>>>,
}
impl RouteService {
@ -123,7 +124,7 @@ impl Service for RouteService {
type Error = Error;
type Future = Either<
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> {
@ -317,7 +318,7 @@ where
type Error = Error;
type InitError = ();
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 {
Box::new(
@ -351,7 +352,7 @@ where
type Error = Error;
type Future = Either<
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> {

View File

@ -23,12 +23,12 @@ use crate::service::{
ServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse,
};
type Guards = Vec<Box<Guard>>;
type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxedService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxedNewService<(), ServiceRequest, ServiceResponse, Error, ()>;
type BoxedResponse = Either<
FutureResult<ServiceResponse, Error>,
Box<Future<Item = ServiceResponse, Error = Error>>,
Box<dyn Future<Item = ServiceResponse, Error = Error>>,
>;
/// Resources scope.
@ -64,8 +64,8 @@ pub struct Scope<T = ScopeEndpoint> {
endpoint: T,
rdef: String,
data: Option<Extensions>,
services: Vec<Box<ServiceFactory>>,
guards: Vec<Box<Guard>>,
services: Vec<Box<dyn ServiceFactory>>,
guards: Vec<Box<dyn Guard>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
external: Vec<ResourceDef>,
factory_ref: Rc<RefCell<Option<ScopeFactory>>>,
@ -195,7 +195,7 @@ where
self.external.extend(cfg.external);
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() {
value.create(&mut data);
@ -425,7 +425,7 @@ where
// complete scope pipeline creation
*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(),
services: Rc::new(
cfg.into_services()
@ -503,10 +503,10 @@ pub struct ScopeFactoryResponse {
fut: Vec<CreateScopeServiceItem>,
data: Option<Rc<Extensions>>,
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 {
Future(Option<ResourceDef>, Option<Guards>, HttpServiceFut),
@ -578,7 +578,7 @@ impl Future for ScopeFactoryResponse {
pub struct ScopeService {
data: Option<Rc<Extensions>>,
router: Router<HttpService, Vec<Box<Guard>>>,
router: Router<HttpService, Vec<Box<dyn Guard>>>,
default: Option<HttpService>,
_ready: Option<(ServiceRequest, ResourceInfo)>,
}
@ -1135,4 +1135,24 @@ mod tests {
let body = read_body(resp);
assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]);
}
#[test]
fn test_url_for_nested() {
let mut srv = init_service(App::new().service(web::scope("/a").service(
web::scope("/b").service(web::resource("/c/{stuff}").name("c").route(
web::get().to(|req: HttpRequest| {
HttpResponse::Ok()
.body(format!("{}", req.url_for("c", &["12345"]).unwrap()))
}),
)),
)));
let req = TestRequest::with_uri("/a/b/c/test").to_request();
let resp = call_service(&mut srv, req);
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp);
assert_eq!(
body,
Bytes::from_static(b"http://localhost:8080/a/b/c/12345")
);
}
}

View File

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

View File

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

Some files were not shown because too many files have changed in this diff Show More