mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-03 09:36:36 +02:00
Compare commits
82 Commits
http-v0.1.
...
files-v0.1
Author | SHA1 | Date | |
---|---|---|---|
bf48798bce | |||
c8118e8411 | |||
e7ba67e1a8 | |||
13e618b128 | |||
36e6f0cb4b | |||
7450ae37a7 | |||
2ffda29f9b | |||
ff724e239d | |||
ee769832cf | |||
c4b7980b4f | |||
bfbac4f875 | |||
53e2f8090f | |||
e399e01a22 | |||
d9a62c4bbf | |||
a548b69679 | |||
ae64475d98 | |||
a342b1289d | |||
38f04b75a7 | |||
a771540b16 | |||
cf217d35a8 | |||
0e138e111f | |||
1fce4876f3 | |||
4a179d1ae1 | |||
a780ea10e9 | |||
6d2e190c8e | |||
b1cfbdcf7a | |||
24180f9014 | |||
15cdc680f6 | |||
666756bfbe | |||
a1b40f4314 | |||
29a0fe76d5 | |||
7753b9da6d | |||
f1764bba43 | |||
c2d7db7e06 | |||
21418c7414 | |||
fe781345d5 | |||
a614be7cb5 | |||
1eb89b8375 | |||
aa626a1e72 | |||
7f12b754e9 | |||
3f196f469d | |||
35eb378585 | |||
6db625f55b | |||
801cc2ed5d | |||
ded1e86e7e | |||
babf48c550 | |||
d3e807f6e9 | |||
7746e785c1 | |||
4e141d7f5d | |||
12842871fe | |||
fc85ae4014 | |||
5826f39dbe | |||
8ff56d7cd5 | |||
0843bce7ba | |||
dea0e0a721 | |||
e857ab1f81 | |||
0dda4b06ea | |||
cbe0226177 | |||
e8c8626878 | |||
4b215e0839 | |||
e1ff3bf8fa | |||
80f4ef9aac | |||
bba90d7f22 | |||
f8af3b86e5 | |||
6c3d8b8738 | |||
5a90e33bcc | |||
86b569e320 | |||
2350a2dc68 | |||
36d017dcc6 | |||
3bb081852c | |||
1ca58e876b | |||
e9cbcbaf03 | |||
07c9eec803 | |||
beae9ca0f7 | |||
07b9707ca1 | |||
45c05978b0 | |||
df08baf67f | |||
4066375737 | |||
a77b0b054a | |||
a17ff492a1 | |||
33b4c05557 | |||
005c055a7f |
71
CHANGES.md
71
CHANGES.md
@ -1,5 +1,76 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.1] - 2019-06-xx
|
||||
|
||||
### Add
|
||||
|
||||
* Add support for PathConfig #903
|
||||
|
||||
* Add `middleware::identity::RequestIdentity` trait to `get_identity` from `HttpMessage`.
|
||||
|
||||
### Changes
|
||||
|
||||
* Disable default feature `secure-cookies`.
|
||||
|
||||
* Move identity middleware to `actix-identity` crate.
|
||||
|
||||
* Allow to test an app that uses async actors #897
|
||||
|
||||
* Re-apply patch from #637 #894
|
||||
|
||||
|
||||
## [1.0.0] - 2019-06-05
|
||||
|
||||
### Add
|
||||
|
||||
* Add `Scope::configure()` method.
|
||||
|
||||
* Add `ServiceRequest::set_payload()` method.
|
||||
|
||||
* Add `test::TestRequest::set_json()` convenience method to automatically
|
||||
serialize data and set header in test requests.
|
||||
|
||||
* Add macros for head, options, trace, connect and patch http methods
|
||||
|
||||
### Changes
|
||||
|
||||
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix Logger request time format, and use rfc3339. #867
|
||||
|
||||
* Clear http requests pool on app service drop #860
|
||||
|
||||
|
||||
## [1.0.0-rc] - 2019-05-18
|
||||
|
||||
### Add
|
||||
|
||||
* 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
|
||||
|
||||
* `JsonConfig` is now `Send + Sync`, this implies that `error_handler` must be `Send + Sync` too.
|
||||
|
||||
### Fixed
|
||||
|
||||
* Codegen with parameters in the path only resolves the first registered endpoint #841
|
||||
|
||||
|
||||
## [1.0.0-beta.4] - 2019-05-12
|
||||
|
||||
### Add
|
||||
|
||||
* Allow to set/override app data on scope level
|
||||
|
||||
### Changes
|
||||
|
||||
* `App::configure` take an `FnOnce` instead of `Fn`
|
||||
* Upgrade actix-net crates
|
||||
|
||||
|
||||
## [1.0.0-beta.3] - 2019-05-04
|
||||
|
||||
### Added
|
||||
|
40
Cargo.toml
40
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "1.0.0-beta.2"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
@ -34,6 +34,7 @@ members = [
|
||||
"actix-files",
|
||||
"actix-framed",
|
||||
"actix-session",
|
||||
"actix-identity",
|
||||
"actix-multipart",
|
||||
"actix-web-actors",
|
||||
"actix-web-codegen",
|
||||
@ -41,7 +42,7 @@ members = [
|
||||
]
|
||||
|
||||
[features]
|
||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client"]
|
||||
default = ["brotli", "flate2-zlib", "client", "fail"]
|
||||
|
||||
# http client
|
||||
client = ["awc"]
|
||||
@ -58,6 +59,8 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
# sessions feature, session require "ring" crate and c compiler
|
||||
secure-cookies = ["actix-http/secure-cookies"]
|
||||
|
||||
fail = ["actix-http/fail"]
|
||||
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
|
||||
@ -66,27 +69,26 @@ rust-tls = ["rustls", "actix-server/rust-tls"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-utils = "0.3.4"
|
||||
actix-router = "0.1.3"
|
||||
actix-service = "0.4.0"
|
||||
actix-utils = "0.4.1"
|
||||
actix-router = "0.1.5"
|
||||
actix-rt = "0.2.2"
|
||||
actix-web-codegen = "0.1.0-beta.1"
|
||||
actix-http = { version = "0.1.4", features=["fail"] }
|
||||
actix-server = "0.4.3"
|
||||
actix-web-codegen = "0.1.2"
|
||||
actix-http = "0.2.3"
|
||||
actix-server = "0.5.1"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
actix = { version = "0.8.1", features=["http"], optional = true }
|
||||
awc = { version = "0.1.1", optional = true }
|
||||
actix-threadpool = "0.1.1"
|
||||
awc = { version = "0.2.1", optional = true }
|
||||
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
encoding = "0.2"
|
||||
futures = "0.1"
|
||||
hashbrown = "0.2.2"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
net2 = "0.2.33"
|
||||
parking_lot = "0.7"
|
||||
parking_lot = "0.8"
|
||||
regex = "1.0"
|
||||
serde = { version = "1.0", features=["derive"] }
|
||||
serde_json = "1.0"
|
||||
@ -96,12 +98,13 @@ url = { version="1.7", features=["query_encoding"] }
|
||||
|
||||
# ssl support
|
||||
openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "^0.15", optional = true }
|
||||
rustls = { version = "0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-http = { version = "0.1.4", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.1.1", features=["ssl"] }
|
||||
actix-files = { version = "0.1.0-beta.1" }
|
||||
actix-http = { version = "0.2.3", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-files = "0.1.1"
|
||||
actix = { version = "0.8.3" }
|
||||
rand = "0.6"
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
@ -122,4 +125,5 @@ actix-web-codegen = { path = "actix-web-codegen" }
|
||||
actix-web-actors = { path = "actix-web-actors" }
|
||||
actix-session = { path = "actix-session" }
|
||||
actix-files = { path = "actix-files" }
|
||||
actix-multipart = { path = "actix-multipart" }
|
||||
awc = { path = "awc" }
|
||||
|
60
MIGRATION.md
60
MIGRATION.md
@ -1,4 +1,21 @@
|
||||
## 1.0
|
||||
## 1.0.1
|
||||
|
||||
* 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
|
||||
|
||||
* Resource registration. 1.0 version uses generalized resource
|
||||
registration via `.service()` method.
|
||||
@ -92,6 +109,36 @@
|
||||
App.new().service(web::resource("/welcome").to(welcome))
|
||||
```
|
||||
|
||||
* `HttpRequest` does not provide access to request's payload stream.
|
||||
|
||||
instead of
|
||||
|
||||
```rust
|
||||
fn index(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
|
||||
req
|
||||
.payload()
|
||||
.from_err()
|
||||
.fold((), |_, chunk| {
|
||||
...
|
||||
})
|
||||
.map(|_| HttpResponse::Ok().finish())
|
||||
.responder()
|
||||
}
|
||||
```
|
||||
|
||||
use `Payload` extractor
|
||||
|
||||
```rust
|
||||
fn index(stream: web::Payload) -> impl Future<Item=HttpResponse, Error=Error> {
|
||||
stream
|
||||
.from_err()
|
||||
.fold((), |_, chunk| {
|
||||
...
|
||||
})
|
||||
.map(|_| HttpResponse::Ok().finish())
|
||||
}
|
||||
```
|
||||
|
||||
* `State` is now `Data`. You register Data during the App initialization process
|
||||
and then access it from handlers either using a Data extractor or using
|
||||
HttpRequest's api.
|
||||
@ -208,6 +255,17 @@
|
||||
|
||||
* Actors support have been moved to `actix-web-actors` crate
|
||||
|
||||
* Custom Error
|
||||
|
||||
Instead of error_response method alone, ResponseError now provides two methods: error_response and render_response respectively. Where, error_response creates the error response and render_response returns the error response to the caller.
|
||||
|
||||
Simplest migration from 0.7 to 1.0 shall include below method to the custom implementation of ResponseError:
|
||||
|
||||
```rust
|
||||
fn render_response(&self) -> HttpResponse {
|
||||
self.error_response()
|
||||
}
|
||||
```
|
||||
|
||||
## 0.7.15
|
||||
|
||||
|
@ -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
|
||||
|
||||
|
@ -1,5 +1,24 @@
|
||||
# Changes
|
||||
|
||||
## [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
|
||||
|
||||
## [0.1.0] - 2019-05-25
|
||||
|
||||
* NamedFile last-modified check always fails due to nano-seconds
|
||||
in file modified date #820
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Update actix-web to beta.4
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Update actix-web to beta.1
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-files"
|
||||
version = "0.1.0-beta.1"
|
||||
version = "0.1.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Static files support for actix web."
|
||||
readme = "README.md"
|
||||
@ -18,8 +18,9 @@ name = "actix_files"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-service = "0.3.4"
|
||||
actix-web = { version = "1.0.0", default-features = false }
|
||||
actix-http = "0.2.3"
|
||||
actix-service = "0.4.0"
|
||||
bitflags = "1"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
@ -31,4 +32,4 @@ percent-encoding = "1.0"
|
||||
v_htmlescape = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-beta.1", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0", features=["ssl"] }
|
||||
|
1
actix-files/LICENSE-APACHE
Symbolic link
1
actix-files/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-files/LICENSE-MIT
Symbolic link
1
actix-files/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -334,6 +334,7 @@ impl Files {
|
||||
where
|
||||
F: IntoNewService<U>,
|
||||
U: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -363,6 +364,7 @@ impl HttpServiceFactory for Files {
|
||||
}
|
||||
|
||||
impl NewService for Files {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -924,6 +926,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);
|
||||
|
||||
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(
|
||||
|
@ -11,6 +11,7 @@ use bitflags::bitflags;
|
||||
use mime;
|
||||
use mime_guess::guess_mime_type;
|
||||
|
||||
use actix_http::body::SizedStream;
|
||||
use actix_web::http::header::{
|
||||
self, ContentDisposition, DispositionParam, DispositionType,
|
||||
};
|
||||
@ -337,7 +338,12 @@ impl Responder for NamedFile {
|
||||
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
|
||||
(last_modified, req.get_header())
|
||||
{
|
||||
m > since
|
||||
let t1: SystemTime = m.clone().into();
|
||||
let t2: SystemTime = since.clone().into();
|
||||
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||
(Ok(t1), Ok(t2)) => t1 > t2,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
@ -350,7 +356,12 @@ impl Responder for NamedFile {
|
||||
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
|
||||
(last_modified, req.get_header())
|
||||
{
|
||||
m <= since
|
||||
let t1: SystemTime = m.clone().into();
|
||||
let t2: SystemTime = since.clone().into();
|
||||
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
|
||||
(Ok(t1), Ok(t2)) => t1 <= t2,
|
||||
_ => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
@ -411,20 +422,16 @@ impl Responder for NamedFile {
|
||||
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
||||
}
|
||||
|
||||
if *req.method() == Method::HEAD {
|
||||
Ok(resp.finish())
|
||||
} else {
|
||||
let reader = ChunkedReadFile {
|
||||
offset,
|
||||
size: length,
|
||||
file: Some(self.file),
|
||||
fut: None,
|
||||
counter: 0,
|
||||
};
|
||||
if offset != 0 || length != self.md.len() {
|
||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||
};
|
||||
Ok(resp.streaming(reader))
|
||||
}
|
||||
let reader = ChunkedReadFile {
|
||||
offset,
|
||||
size: length,
|
||||
file: Some(self.file),
|
||||
fut: None,
|
||||
counter: 0,
|
||||
};
|
||||
if offset != 0 || length != self.md.len() {
|
||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||
};
|
||||
Ok(resp.body(SizedStream::new(length, reader)))
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-framed"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix framed app server"
|
||||
readme = "README.md"
|
||||
@ -21,17 +21,18 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-utils = "0.3.4"
|
||||
actix-service = "0.4.0"
|
||||
actix-utils = "0.4.0"
|
||||
actix-router = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.1.0"
|
||||
actix-http = "0.2.0"
|
||||
actix-server-config = "0.1.1"
|
||||
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
|
@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
* Update dependencies
|
||||
|
||||
|
||||
## [0.1.0] - 2019-04-16
|
||||
|
||||
* Update tests
|
||||
|
@ -4,6 +4,7 @@ use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_http::h1::{Codec, SendResponse};
|
||||
use actix_http::{Error, Request, Response};
|
||||
use actix_router::{Path, Router, Url};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use actix_utils::cloneable::CloneableService;
|
||||
use futures::{Async, Future, Poll};
|
||||
@ -49,6 +50,7 @@ impl<T: 'static, S: 'static> FramedApp<T, S> {
|
||||
where
|
||||
U: HttpServiceFactory,
|
||||
U::Factory: NewService<
|
||||
Config = (),
|
||||
Request = FramedRequest<T, S>,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
@ -88,11 +90,12 @@ pub struct FramedAppFactory<T, S> {
|
||||
services: Rc<Vec<(String, BoxedHttpNewService<FramedRequest<T, S>>)>>,
|
||||
}
|
||||
|
||||
impl<T, S, C> NewService<C> for FramedAppFactory<T, S>
|
||||
impl<T, S> NewService for FramedAppFactory<T, S>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
S: 'static,
|
||||
{
|
||||
type Config = ServerConfig;
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
@ -100,7 +103,7 @@ where
|
||||
type Service = CloneableService<FramedAppService<T, S>>;
|
||||
type Future = CreateService<T, S>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
CreateService {
|
||||
fut: self
|
||||
.services
|
||||
|
@ -13,6 +13,7 @@ pub(crate) type BoxedHttpService<Req> = Box<
|
||||
|
||||
pub(crate) type BoxedHttpNewService<Req> = Box<
|
||||
NewService<
|
||||
Config = (),
|
||||
Request = Req,
|
||||
Response = (),
|
||||
Error = Error,
|
||||
@ -39,12 +40,13 @@ where
|
||||
|
||||
impl<T> NewService for HttpNewService<T>
|
||||
where
|
||||
T: NewService<Response = (), Error = Error>,
|
||||
T: NewService<Config = (), Response = (), Error = Error>,
|
||||
T::Request: 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: Service<Future = Box<Future<Item = (), Error = Error>>> + 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Config = ();
|
||||
type Request = T::Request;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
|
@ -106,6 +106,7 @@ where
|
||||
R::Future: 'static,
|
||||
R::Error: fmt::Display,
|
||||
{
|
||||
type Config = ();
|
||||
type Request = FramedRequest<Io, S>;
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
|
@ -12,22 +12,23 @@ use futures::{Async, Future, IntoFuture, Poll, Sink};
|
||||
|
||||
/// Service that verifies incoming request if it is valid websocket
|
||||
/// upgrade request. In case of error returns `HandshakeError`
|
||||
pub struct VerifyWebSockets<T> {
|
||||
_t: PhantomData<T>,
|
||||
pub struct VerifyWebSockets<T, C> {
|
||||
_t: PhantomData<(T, C)>,
|
||||
}
|
||||
|
||||
impl<T> Default for VerifyWebSockets<T> {
|
||||
impl<T, C> Default for VerifyWebSockets<T, C> {
|
||||
fn default() -> Self {
|
||||
VerifyWebSockets { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
||||
impl<T, C> NewService for VerifyWebSockets<T, C> {
|
||||
type Config = C;
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
type Error = (HandshakeError, Framed<T, Codec>);
|
||||
type InitError = ();
|
||||
type Service = VerifyWebSockets<T>;
|
||||
type Service = VerifyWebSockets<T, C>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
@ -35,7 +36,7 @@ impl<T, C> NewService<C> for VerifyWebSockets<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for VerifyWebSockets<T> {
|
||||
impl<T, C> Service for VerifyWebSockets<T, C> {
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
type Error = (HandshakeError, Framed<T, Codec>);
|
||||
@ -54,9 +55,9 @@ impl<T> Service for VerifyWebSockets<T> {
|
||||
}
|
||||
|
||||
/// Send http/1 error response
|
||||
pub struct SendError<T, R, E>(PhantomData<(T, R, E)>);
|
||||
pub struct SendError<T, R, E, C>(PhantomData<(T, R, E, C)>);
|
||||
|
||||
impl<T, R, E> Default for SendError<T, R, E>
|
||||
impl<T, R, E, C> Default for SendError<T, R, E, C>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
E: ResponseError,
|
||||
@ -66,17 +67,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, R, E, C> NewService<C> for SendError<T, R, E>
|
||||
impl<T, R, E, C> NewService for SendError<T, R, E, C>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
R: 'static,
|
||||
E: ResponseError + 'static,
|
||||
{
|
||||
type Config = C;
|
||||
type Request = Result<R, (E, Framed<T, Codec>)>;
|
||||
type Response = R;
|
||||
type Error = (E, Framed<T, Codec>);
|
||||
type InitError = ();
|
||||
type Service = SendError<T, R, E>;
|
||||
type Service = SendError<T, R, E, C>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
@ -84,7 +86,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, R, E> Service for SendError<T, R, E>
|
||||
impl<T, R, E, C> Service for SendError<T, R, E, C>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + 'static,
|
||||
R: 'static,
|
||||
|
@ -1,5 +1,45 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.3] - 2019-06-02
|
||||
|
||||
### Added
|
||||
|
||||
* Debug impl for ResponseBuilder
|
||||
|
||||
* From SizedStream and BodyStream for Body
|
||||
|
||||
### Changed
|
||||
|
||||
* SizedStream uses u64
|
||||
|
||||
|
||||
## [0.2.2] - 2019-05-29
|
||||
|
||||
### Fixed
|
||||
|
||||
* Parse incoming stream before closing stream on disconnect #868
|
||||
|
||||
|
||||
## [0.2.1] - 2019-05-25
|
||||
|
||||
### Fixed
|
||||
|
||||
* Handle socket read disconnect
|
||||
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Update actix-service to 0.4
|
||||
|
||||
* Expect and upgrade services accept `ServerConfig` config.
|
||||
|
||||
### Deleted
|
||||
|
||||
* `OneRequest` service
|
||||
|
||||
|
||||
## [0.1.5] - 2019-05-04
|
||||
|
||||
### Fixed
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "0.1.5"
|
||||
version = "0.2.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http primitives"
|
||||
readme = "README.md"
|
||||
@ -44,10 +44,10 @@ fail = ["failure"]
|
||||
secure-cookies = ["ring"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.3.6"
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.2"
|
||||
actix-connect = "0.1.5"
|
||||
actix-utils = "0.3.5"
|
||||
actix-connect = "0.2.0"
|
||||
actix-utils = "0.4.1"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
|
||||
@ -59,8 +59,8 @@ copyless = "0.1.2"
|
||||
derive_more = "0.14"
|
||||
either = "1.5.2"
|
||||
encoding = "0.2"
|
||||
futures = "0.1"
|
||||
hashbrown = "0.2.2"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
h2 = "0.1.16"
|
||||
http = "0.1.17"
|
||||
httparse = "1.3"
|
||||
@ -81,7 +81,7 @@ time = "0.1.42"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-timer = "0.2.8"
|
||||
tokio-current-thread = "0.1"
|
||||
trust-dns-resolver = { version="0.11.0", default-features = false }
|
||||
trust-dns-resolver = { version="0.11.1", default-features = false }
|
||||
|
||||
# for secure cookie
|
||||
ring = { version = "0.14.6", optional = true }
|
||||
@ -97,9 +97,9 @@ chrono = "0.4.6"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
||||
actix-connect = { version = "0.1.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-connect = { version = "0.2.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
openssl = { version="0.10" }
|
||||
|
@ -234,6 +234,25 @@ impl From<BytesMut> for Body {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<SizedStream<S>> for Body
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = Error> + 'static,
|
||||
{
|
||||
fn from(s: SizedStream<S>) -> Body {
|
||||
Body::from_message(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, E> From<BodyStream<S, E>> for Body
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = E> + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
fn from(s: BodyStream<S, E>) -> Body {
|
||||
Body::from_message(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl MessageBody for Bytes {
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len())
|
||||
@ -366,7 +385,7 @@ where
|
||||
/// Type represent streaming body. This body implementation should be used
|
||||
/// if total size of stream is known. Data get sent as is without using transfer encoding.
|
||||
pub struct SizedStream<S> {
|
||||
size: usize,
|
||||
size: u64,
|
||||
stream: S,
|
||||
}
|
||||
|
||||
@ -374,7 +393,7 @@ impl<S> SizedStream<S>
|
||||
where
|
||||
S: Stream<Item = Bytes, Error = Error>,
|
||||
{
|
||||
pub fn new(size: usize, stream: S) -> Self {
|
||||
pub fn new(size: u64, stream: S) -> Self {
|
||||
SizedStream { size, stream }
|
||||
}
|
||||
}
|
||||
@ -384,7 +403,7 @@ where
|
||||
S: Stream<Item = Bytes, Error = Error>,
|
||||
{
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.size)
|
||||
BodySize::Sized64(self.size)
|
||||
}
|
||||
|
||||
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
||||
|
@ -29,7 +29,7 @@ pub struct HttpServiceBuilder<T, S, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
|
||||
impl<T, S> HttpServiceBuilder<T, S, ExpectHandler, UpgradeHandler<T>>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
{
|
||||
@ -48,13 +48,17 @@ where
|
||||
|
||||
impl<T, S, X, U> HttpServiceBuilder<T, S, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||
U: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U::Error: fmt::Display,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
@ -101,7 +105,7 @@ where
|
||||
pub fn expect<F, X1>(self, expect: F) -> HttpServiceBuilder<T, S, X1, U>
|
||||
where
|
||||
F: IntoNewService<X1>,
|
||||
X1: NewService<Request = Request, Response = Request>,
|
||||
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X1::Error: Into<Error>,
|
||||
X1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -122,7 +126,11 @@ where
|
||||
pub fn upgrade<F, U1>(self, upgrade: F) -> HttpServiceBuilder<T, S, X, U1>
|
||||
where
|
||||
F: IntoNewService<U1>,
|
||||
U1: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||
U1: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U1::Error: fmt::Display,
|
||||
U1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -140,7 +148,7 @@ where
|
||||
pub fn h1<F, P, B>(self, service: F) -> H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoNewService<S, SrvConfig>,
|
||||
F: IntoNewService<S>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -159,7 +167,7 @@ where
|
||||
pub fn h2<F, P, B>(self, service: F) -> H2Service<T, P, S, B>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoNewService<S, SrvConfig>,
|
||||
F: IntoNewService<S>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -177,7 +185,7 @@ where
|
||||
pub fn finish<F, P, B>(self, service: F) -> HttpService<T, P, S, B, X, U>
|
||||
where
|
||||
B: MessageBody + 'static,
|
||||
F: IntoNewService<S, SrvConfig>,
|
||||
F: IntoNewService<S>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
@ -158,7 +158,8 @@ impl ServiceConfig {
|
||||
self.0.timer.now()
|
||||
}
|
||||
|
||||
pub(crate) fn set_date(&self, dst: &mut BytesMut) {
|
||||
#[doc(hidden)]
|
||||
pub fn set_date(&self, dst: &mut BytesMut) {
|
||||
let mut buf: [u8; 39] = [0; 39];
|
||||
buf[..6].copy_from_slice(b"date: ");
|
||||
buf[6..35].copy_from_slice(&self.0.timer.date().bytes);
|
||||
|
@ -31,7 +31,7 @@ const AVERAGE_HEADER_SIZE: usize = 30;
|
||||
|
||||
/// HTTP/1 Codec
|
||||
pub struct Codec {
|
||||
pub(crate) config: ServiceConfig,
|
||||
config: ServiceConfig,
|
||||
decoder: decoder::MessageDecoder<Request>,
|
||||
payload: Option<PayloadDecoder>,
|
||||
version: Version,
|
||||
@ -104,6 +104,11 @@ impl Codec {
|
||||
MessageType::Payload
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn config(&self) -> &ServiceConfig {
|
||||
&self.config
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for Codec {
|
||||
|
@ -567,7 +567,7 @@ where
|
||||
}
|
||||
|
||||
if updated && self.ka_timer.is_some() {
|
||||
if let Some(expire) = self.codec.config.keep_alive_expire() {
|
||||
if let Some(expire) = self.codec.config().keep_alive_expire() {
|
||||
self.ka_expire = expire;
|
||||
}
|
||||
}
|
||||
@ -579,10 +579,13 @@ where
|
||||
if self.ka_timer.is_none() {
|
||||
// shutdown timeout
|
||||
if self.flags.contains(Flags::SHUTDOWN) {
|
||||
if let Some(interval) = self.codec.config.client_disconnect_timer() {
|
||||
if let Some(interval) = self.codec.config().client_disconnect_timer() {
|
||||
self.ka_timer = Some(Delay::new(interval));
|
||||
} else {
|
||||
self.flags.insert(Flags::READ_DISCONNECT);
|
||||
if let Some(mut payload) = self.payload.take() {
|
||||
payload.set_error(PayloadError::Incomplete(None));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
@ -607,7 +610,7 @@ where
|
||||
|
||||
// start shutdown timer
|
||||
if let Some(deadline) =
|
||||
self.codec.config.client_disconnect_timer()
|
||||
self.codec.config().client_disconnect_timer()
|
||||
{
|
||||
if let Some(timer) = self.ka_timer.as_mut() {
|
||||
timer.reset(deadline);
|
||||
@ -632,7 +635,8 @@ where
|
||||
self.flags.insert(Flags::STARTED | Flags::SHUTDOWN);
|
||||
self.state = State::None;
|
||||
}
|
||||
} else if let Some(deadline) = self.codec.config.keep_alive_expire()
|
||||
} else if let Some(deadline) =
|
||||
self.codec.config().keep_alive_expire()
|
||||
{
|
||||
if let Some(timer) = self.ka_timer.as_mut() {
|
||||
timer.reset(deadline);
|
||||
@ -689,15 +693,21 @@ where
|
||||
}
|
||||
} else {
|
||||
// read socket into a buf
|
||||
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||
if let Some(true) =
|
||||
let should_disconnect =
|
||||
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||
read_available(&mut inner.io, &mut inner.read_buf)?
|
||||
{
|
||||
inner.flags.insert(Flags::READ_DISCONNECT)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
inner.poll_request()?;
|
||||
if let Some(true) = should_disconnect {
|
||||
inner.flags.insert(Flags::READ_DISCONNECT);
|
||||
if let Some(mut payload) = inner.payload.take() {
|
||||
payload.feed_eof();
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
if inner.write_buf.remaining_mut() < LW_BUFFER_SIZE {
|
||||
inner.write_buf.reserve(HW_BUFFER_SIZE);
|
||||
|
@ -1,3 +1,4 @@
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Poll};
|
||||
@ -8,6 +9,7 @@ use crate::request::Request;
|
||||
pub struct ExpectHandler;
|
||||
|
||||
impl NewService for ExpectHandler {
|
||||
type Config = ServerConfig;
|
||||
type Request = Request;
|
||||
type Response = Request;
|
||||
type Error = Error;
|
||||
@ -15,7 +17,7 @@ impl NewService for ExpectHandler {
|
||||
type InitError = Error;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
ok(ExpectHandler)
|
||||
}
|
||||
}
|
||||
|
@ -29,14 +29,14 @@ pub struct H1Service<T, P, S, B, X = ExpectHandler, U = UpgradeHandler<T>> {
|
||||
|
||||
impl<T, P, S, B> H1Service<T, P, S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
B: MessageBody,
|
||||
{
|
||||
/// Create new `HttpService` instance with default config.
|
||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
||||
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||
|
||||
H1Service {
|
||||
@ -49,10 +49,7 @@ where
|
||||
}
|
||||
|
||||
/// Create new `HttpService` instance with config.
|
||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
||||
cfg: ServiceConfig,
|
||||
service: F,
|
||||
) -> Self {
|
||||
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||
H1Service {
|
||||
cfg,
|
||||
srv: service.into_new_service(),
|
||||
@ -65,7 +62,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
S::InitError: fmt::Debug,
|
||||
@ -102,21 +99,26 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for H1Service<T, P, S, B, X, U>
|
||||
impl<T, P, S, B, X, U> NewService for H1Service<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
S::InitError: fmt::Debug,
|
||||
B: MessageBody,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
U: NewService<Request = (Request, Framed<T, Codec>), Response = ()>,
|
||||
U: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U::Error: fmt::Display,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = Io<T, P>;
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -127,8 +129,8 @@ where
|
||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||
H1ServiceResponse {
|
||||
fut: self.srv.new_service(cfg).into_future(),
|
||||
fut_ex: Some(self.expect.new_service(&())),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
||||
fut_ex: Some(self.expect.new_service(cfg)),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||
expect: None,
|
||||
upgrade: None,
|
||||
cfg: Some(self.cfg.clone()),
|
||||
@ -140,7 +142,7 @@ where
|
||||
#[doc(hidden)]
|
||||
pub struct H1ServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
@ -162,7 +164,7 @@ where
|
||||
impl<T, P, S, B, X, U> Future for H1ServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
S::InitError: fmt::Debug,
|
||||
@ -320,10 +322,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P> NewService<SrvConfig> for OneRequest<T, P>
|
||||
impl<T, P> NewService for OneRequest<T, P>
|
||||
where
|
||||
T: IoStream,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = Io<T, P>;
|
||||
type Response = (Request, Framed<T, Codec>);
|
||||
type Error = ParseError;
|
||||
|
@ -1,6 +1,7 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use actix_codec::Framed;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::FutureResult;
|
||||
use futures::{Async, Poll};
|
||||
@ -12,6 +13,7 @@ use crate::request::Request;
|
||||
pub struct UpgradeHandler<T>(PhantomData<T>);
|
||||
|
||||
impl<T> NewService for UpgradeHandler<T> {
|
||||
type Config = ServerConfig;
|
||||
type Request = (Request, Framed<T, Codec>);
|
||||
type Response = ();
|
||||
type Error = Error;
|
||||
@ -19,7 +21,7 @@ impl<T> NewService for UpgradeHandler<T> {
|
||||
type InitError = Error;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
fn new_service(&self, _: &ServerConfig) -> Self::Future {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
@ -31,14 +31,14 @@ pub struct H2Service<T, P, S, B> {
|
||||
|
||||
impl<T, P, S, B> H2Service<T, P, S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
/// Create new `HttpService` instance.
|
||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
||||
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||
|
||||
H2Service {
|
||||
@ -49,10 +49,7 @@ where
|
||||
}
|
||||
|
||||
/// Create new `HttpService` instance with config.
|
||||
pub fn with_config<F: IntoNewService<S, SrvConfig>>(
|
||||
cfg: ServiceConfig,
|
||||
service: F,
|
||||
) -> Self {
|
||||
pub fn with_config<F: IntoNewService<S>>(cfg: ServiceConfig, service: F) -> Self {
|
||||
H2Service {
|
||||
cfg,
|
||||
srv: service.into_new_service(),
|
||||
@ -61,15 +58,16 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P, S, B> NewService<SrvConfig> for H2Service<T, P, S, B>
|
||||
impl<T, P, S, B> NewService for H2Service<T, P, S, B>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = Io<T, P>;
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -87,7 +85,7 @@ where
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>, B> {
|
||||
pub struct H2ServiceResponse<T, P, S: NewService, B> {
|
||||
fut: <S::Future as IntoFuture>::Future,
|
||||
cfg: Option<ServiceConfig>,
|
||||
_t: PhantomData<(T, P, B)>,
|
||||
@ -96,7 +94,7 @@ pub struct H2ServiceResponse<T, P, S: NewService<SrvConfig, Request = Request>,
|
||||
impl<T, P, S, B> Future for H2ServiceResponse<T, P, S, B>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
|
@ -764,6 +764,25 @@ impl IntoFuture for ResponseBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ResponseBuilder {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let head = self.head.as_ref().unwrap();
|
||||
|
||||
let res = writeln!(
|
||||
f,
|
||||
"\nResponseBuilder {:?} {}{}",
|
||||
head.version,
|
||||
head.status,
|
||||
head.reason.unwrap_or(""),
|
||||
);
|
||||
let _ = writeln!(f, " headers:");
|
||||
for (key, val) in head.headers.iter() {
|
||||
let _ = writeln!(f, " {:?}: {:?}", key, val);
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper converters
|
||||
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
||||
fn from(res: Result<I, E>) -> Self {
|
||||
|
@ -30,7 +30,7 @@ pub struct HttpService<T, P, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler
|
||||
|
||||
impl<T, S, B> HttpService<T, (), S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -45,7 +45,7 @@ where
|
||||
|
||||
impl<T, P, S, B> HttpService<T, P, S, B>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -53,7 +53,7 @@ where
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
/// Create new `HttpService` instance.
|
||||
pub fn new<F: IntoNewService<S, SrvConfig>>(service: F) -> Self {
|
||||
pub fn new<F: IntoNewService<S>>(service: F) -> Self {
|
||||
let cfg = ServiceConfig::new(KeepAlive::Timeout(5), 5000, 0);
|
||||
|
||||
HttpService {
|
||||
@ -66,7 +66,7 @@ where
|
||||
}
|
||||
|
||||
/// Create new `HttpService` instance with config.
|
||||
pub(crate) fn with_config<F: IntoNewService<S, SrvConfig>>(
|
||||
pub(crate) fn with_config<F: IntoNewService<S>>(
|
||||
cfg: ServiceConfig,
|
||||
service: F,
|
||||
) -> Self {
|
||||
@ -82,7 +82,7 @@ where
|
||||
|
||||
impl<T, P, S, B, X, U> HttpService<T, P, S, B, X, U>
|
||||
where
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -95,7 +95,7 @@ where
|
||||
/// request will be forwarded to main service.
|
||||
pub fn expect<X1>(self, expect: X1) -> HttpService<T, P, S, B, X1, U>
|
||||
where
|
||||
X1: NewService<Request = Request, Response = Request>,
|
||||
X1: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X1::Error: Into<Error>,
|
||||
X1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -114,7 +114,11 @@ where
|
||||
/// and this service get called with original request and framed object.
|
||||
pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, P, S, B, X, U1>
|
||||
where
|
||||
U1: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U1: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, h1::Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U1::Error: fmt::Display,
|
||||
U1::InitError: fmt::Debug,
|
||||
{
|
||||
@ -128,22 +132,27 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P, S, B, X, U> NewService<SrvConfig> for HttpService<T, P, S, B, X, U>
|
||||
impl<T, P, S, B, X, U> NewService for HttpService<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Config = SrvConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
B: MessageBody + 'static,
|
||||
X: NewService<Request = Request, Response = Request>,
|
||||
X: NewService<Config = SrvConfig, Request = Request, Response = Request>,
|
||||
X::Error: Into<Error>,
|
||||
X::InitError: fmt::Debug,
|
||||
U: NewService<Request = (Request, Framed<T, h1::Codec>), Response = ()>,
|
||||
U: NewService<
|
||||
Config = SrvConfig,
|
||||
Request = (Request, Framed<T, h1::Codec>),
|
||||
Response = (),
|
||||
>,
|
||||
U::Error: fmt::Display,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
type Config = SrvConfig;
|
||||
type Request = ServerIo<T, P>;
|
||||
type Response = ();
|
||||
type Error = DispatchError;
|
||||
@ -154,8 +163,8 @@ where
|
||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||
HttpServiceResponse {
|
||||
fut: self.srv.new_service(cfg).into_future(),
|
||||
fut_ex: Some(self.expect.new_service(&())),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(&())),
|
||||
fut_ex: Some(self.expect.new_service(cfg)),
|
||||
fut_upg: self.upgrade.as_ref().map(|f| f.new_service(cfg)),
|
||||
expect: None,
|
||||
upgrade: None,
|
||||
cfg: Some(self.cfg.clone()),
|
||||
@ -165,14 +174,7 @@ where
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct HttpServiceResponse<
|
||||
T,
|
||||
P,
|
||||
S: NewService<SrvConfig>,
|
||||
B,
|
||||
X: NewService,
|
||||
U: NewService,
|
||||
> {
|
||||
pub struct HttpServiceResponse<T, P, S: NewService, B, X: NewService, U: NewService> {
|
||||
fut: S::Future,
|
||||
fut_ex: Option<X::Future>,
|
||||
fut_upg: Option<U::Future>,
|
||||
@ -185,7 +187,7 @@ pub struct HttpServiceResponse<
|
||||
impl<T, P, S, B, X, U> Future for HttpServiceResponse<T, P, S, B, X, U>
|
||||
where
|
||||
T: IoStream,
|
||||
S: NewService<SrvConfig, Request = Request>,
|
||||
S: NewService<Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
@ -5,13 +5,13 @@ use std::{net, thread};
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{fn_cfg_factory, fn_service, NewService};
|
||||
use actix_service::{new_service_cfg, service_fn, NewService};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{self, ok, Future};
|
||||
use futures::stream::{once, Stream};
|
||||
use regex::Regex;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use actix_http::body::Body;
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::{
|
||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
||||
@ -163,7 +163,7 @@ fn test_h2_body() -> std::io::Result<()> {
|
||||
fn test_expect_continue() {
|
||||
let srv = TestServer::new(|| {
|
||||
HttpService::build()
|
||||
.expect(fn_service(|req: Request| {
|
||||
.expect(service_fn(|req: Request| {
|
||||
if req.head().uri.query() == Some("yes=") {
|
||||
Ok(req)
|
||||
} else {
|
||||
@ -190,7 +190,7 @@ fn test_expect_continue() {
|
||||
fn test_expect_continue_h1() {
|
||||
let srv = TestServer::new(|| {
|
||||
HttpService::build()
|
||||
.expect(fn_service(|req: Request| {
|
||||
.expect(service_fn(|req: Request| {
|
||||
sleep(Duration::from_millis(20)).then(move |_| {
|
||||
if req.head().uri.query() == Some("yes=") {
|
||||
Ok(req)
|
||||
@ -215,6 +215,54 @@ fn test_expect_continue_h1() {
|
||||
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chunked_payload() {
|
||||
let chunk_sizes = vec![32768, 32, 32768];
|
||||
let total_size: usize = chunk_sizes.iter().sum();
|
||||
|
||||
let srv = TestServer::new(|| {
|
||||
HttpService::build().h1(|mut request: Request| {
|
||||
request
|
||||
.take_payload()
|
||||
.map_err(|e| panic!(format!("Error reading payload: {}", e)))
|
||||
.fold(0usize, |acc, chunk| future::ok::<_, ()>(acc + chunk.len()))
|
||||
.map(|req_size| Response::Ok().body(format!("size={}", req_size)))
|
||||
})
|
||||
});
|
||||
|
||||
let returned_size = {
|
||||
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
|
||||
let _ = stream
|
||||
.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n");
|
||||
|
||||
for chunk_size in chunk_sizes.iter() {
|
||||
let mut bytes = Vec::new();
|
||||
let random_bytes: Vec<u8> =
|
||||
(0..*chunk_size).map(|_| rand::random::<u8>()).collect();
|
||||
|
||||
bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes());
|
||||
bytes.extend(&random_bytes[..]);
|
||||
bytes.extend(b"\r\n");
|
||||
let _ = stream.write_all(&bytes);
|
||||
}
|
||||
|
||||
let _ = stream.write_all(b"0\r\n\r\n");
|
||||
stream.shutdown(net::Shutdown::Write).unwrap();
|
||||
|
||||
let mut data = String::new();
|
||||
let _ = stream.read_to_string(&mut data);
|
||||
|
||||
let re = Regex::new(r"size=(\d+)").unwrap();
|
||||
let size: usize = match re.captures(&data) {
|
||||
Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
|
||||
None => panic!(format!("Failed to find size in HTTP Response: {}", data)),
|
||||
};
|
||||
size
|
||||
};
|
||||
|
||||
assert_eq!(returned_size, total_size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_slow_request() {
|
||||
let srv = TestServer::new(|| {
|
||||
@ -775,8 +823,7 @@ fn test_h1_body_length() {
|
||||
HttpService::build().h1(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(Body::from_message(body::SizedStream::new(STR.len(), body))),
|
||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
});
|
||||
@ -801,9 +848,10 @@ fn test_h2_body_length() {
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(Response::Ok().body(Body::from_message(
|
||||
body::SizedStream::new(STR.len(), body),
|
||||
)))
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
@ -912,7 +960,7 @@ fn test_h1_body_chunked_implicit() {
|
||||
#[test]
|
||||
fn test_h1_response_http_error_handling() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::build().h1(fn_cfg_factory(|_: &ServerConfig| {
|
||||
HttpService::build().h1(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
@ -943,7 +991,7 @@ fn test_h2_response_http_error_handling() {
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
.and_then(
|
||||
HttpService::build()
|
||||
.h2(fn_cfg_factory(|_: &ServerConfig| {
|
||||
.h2(new_service_cfg(|_: &ServerConfig| {
|
||||
Ok::<_, ()>(|_| {
|
||||
let broken_header = Bytes::from_static(b"\0\0\0");
|
||||
ok::<_, ()>(
|
||||
|
5
actix-identity/CHANGES.md
Normal file
5
actix-identity/CHANGES.md
Normal 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
30
actix-identity/Cargo.toml
Normal 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"
|
1
actix-identity/LICENSE-APACHE
Symbolic link
1
actix-identity/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-identity/LICENSE-MIT
Symbolic link
1
actix-identity/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
9
actix-identity/README.md
Normal file
9
actix-identity/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](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
|
@ -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(
|
||||
@ -442,9 +462,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(
|
||||
@ -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()
|
@ -1,5 +1,27 @@
|
||||
# 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
|
||||
|
||||
## [0.1.1] - 2019-05-25
|
||||
|
||||
* Fix disconnect handling #834
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Release
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Handle cancellation of uploads #736
|
||||
|
||||
* Upgrade to actix-web 1.0.0-beta.4
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-21
|
||||
|
||||
* Do not support nested multipart
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-multipart"
|
||||
version = "0.1.0-beta.1"
|
||||
version = "0.1.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Multipart support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -18,8 +18,8 @@ name = "actix_multipart"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-service = "0.3.6"
|
||||
actix-web = { version = "1.0.0", default-features = false }
|
||||
actix-service = "0.4.0"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
httparse = "1.3"
|
||||
@ -31,4 +31,4 @@ twoway = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.1.1"
|
||||
actix-http = "0.2.2"
|
1
actix-multipart/LICENSE-APACHE
Symbolic link
1
actix-multipart/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-multipart/LICENSE-MIT
Symbolic link
1
actix-multipart/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -28,6 +28,9 @@ pub enum MultipartError {
|
||||
/// Payload error
|
||||
#[display(fmt = "{}", _0)]
|
||||
Payload(PayloadError),
|
||||
/// Not consumed
|
||||
#[display(fmt = "Multipart stream is not consumed")]
|
||||
NotConsumed,
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `MultipartError`
|
||||
|
@ -1,5 +1,5 @@
|
||||
//! Multipart payload support
|
||||
use std::cell::{RefCell, UnsafeCell};
|
||||
use std::cell::{Cell, RefCell, UnsafeCell};
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
use std::{cmp, fmt};
|
||||
@ -116,6 +116,8 @@ impl Stream for Multipart {
|
||||
payload.poll_stream()?;
|
||||
}
|
||||
inner.poll(&self.safety)
|
||||
} else if !self.safety.is_clean() {
|
||||
Err(MultipartError::NotConsumed)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@ -126,7 +128,7 @@ impl InnerMultipart {
|
||||
fn read_headers(
|
||||
payload: &mut PayloadBuffer,
|
||||
) -> Result<Option<HeaderMap>, MultipartError> {
|
||||
match payload.read_until(b"\r\n\r\n") {
|
||||
match payload.read_until(b"\r\n\r\n")? {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
@ -165,7 +167,7 @@ impl InnerMultipart {
|
||||
boundary: &str,
|
||||
) -> Result<Option<bool>, MultipartError> {
|
||||
// TODO: need to read epilogue
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
None => {
|
||||
if payload.eof {
|
||||
Ok(Some(true))
|
||||
@ -198,7 +200,7 @@ impl InnerMultipart {
|
||||
) -> Result<Option<bool>, MultipartError> {
|
||||
let mut eof = false;
|
||||
loop {
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
Some(chunk) => {
|
||||
if chunk.is_empty() {
|
||||
return Err(MultipartError::Boundary);
|
||||
@ -415,6 +417,8 @@ impl Stream for Field {
|
||||
}
|
||||
|
||||
inner.poll(&self.safety)
|
||||
} else if !self.safety.is_clean() {
|
||||
return Err(MultipartError::NotConsumed);
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@ -477,7 +481,7 @@ impl InnerField {
|
||||
if *size == 0 {
|
||||
Ok(Async::Ready(None))
|
||||
} else {
|
||||
match payload.read_max(*size) {
|
||||
match payload.read_max(*size)? {
|
||||
Some(mut chunk) => {
|
||||
let len = cmp::min(chunk.len() as u64, *size);
|
||||
*size -= len;
|
||||
@ -508,7 +512,11 @@ impl InnerField {
|
||||
|
||||
let len = payload.buf.len();
|
||||
if len == 0 {
|
||||
return Ok(Async::NotReady);
|
||||
return if payload.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
};
|
||||
}
|
||||
|
||||
// check boundary
|
||||
@ -529,8 +537,6 @@ impl InnerField {
|
||||
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
} else {
|
||||
pos = b_size;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -568,7 +574,7 @@ impl InnerField {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Ok(Async::Ready(Some(payload.buf.take().freeze())));
|
||||
Ok(Async::Ready(Some(payload.buf.take().freeze())))
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -593,7 +599,7 @@ impl InnerField {
|
||||
}
|
||||
}
|
||||
|
||||
match payload.readline() {
|
||||
match payload.readline()? {
|
||||
None => Async::Ready(None),
|
||||
Some(line) => {
|
||||
if line.as_ref() != b"\r\n" {
|
||||
@ -655,6 +661,7 @@ struct Safety {
|
||||
task: Option<Task>,
|
||||
level: usize,
|
||||
payload: Rc<PhantomData<bool>>,
|
||||
clean: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl Safety {
|
||||
@ -663,12 +670,17 @@ impl Safety {
|
||||
Safety {
|
||||
task: None,
|
||||
level: Rc::strong_count(&payload),
|
||||
clean: Rc::new(Cell::new(true)),
|
||||
payload,
|
||||
}
|
||||
}
|
||||
|
||||
fn current(&self) -> bool {
|
||||
Rc::strong_count(&self.payload) == self.level
|
||||
Rc::strong_count(&self.payload) == self.level && self.clean.get()
|
||||
}
|
||||
|
||||
fn is_clean(&self) -> bool {
|
||||
self.clean.get()
|
||||
}
|
||||
}
|
||||
|
||||
@ -678,6 +690,7 @@ impl Clone for Safety {
|
||||
Safety {
|
||||
task: Some(current_task()),
|
||||
level: Rc::strong_count(&payload),
|
||||
clean: self.clean.clone(),
|
||||
payload,
|
||||
}
|
||||
}
|
||||
@ -687,7 +700,7 @@ impl Drop for Safety {
|
||||
fn drop(&mut self) {
|
||||
// parent task is dead
|
||||
if Rc::strong_count(&self.payload) != self.level {
|
||||
panic!("Safety get dropped but it is not from top-most task");
|
||||
self.clean.set(true);
|
||||
}
|
||||
if let Some(task) = self.task.take() {
|
||||
task.notify()
|
||||
@ -738,23 +751,31 @@ impl PayloadBuffer {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_max(&mut self, size: u64) -> Option<Bytes> {
|
||||
fn read_max(&mut self, size: u64) -> Result<Option<Bytes>, MultipartError> {
|
||||
if !self.buf.is_empty() {
|
||||
let size = std::cmp::min(self.buf.len() as u64, size) as usize;
|
||||
Some(self.buf.split_to(size).freeze())
|
||||
Ok(Some(self.buf.split_to(size).freeze()))
|
||||
} else if self.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
None
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read until specified ending
|
||||
pub fn read_until(&mut self, line: &[u8]) -> Option<Bytes> {
|
||||
twoway::find_bytes(&self.buf, line)
|
||||
.map(|idx| self.buf.split_to(idx + line.len()).freeze())
|
||||
pub fn read_until(&mut self, line: &[u8]) -> Result<Option<Bytes>, MultipartError> {
|
||||
let res = twoway::find_bytes(&self.buf, line)
|
||||
.map(|idx| self.buf.split_to(idx + line.len()).freeze());
|
||||
|
||||
if res.is_none() && self.eof {
|
||||
Err(MultipartError::Incomplete)
|
||||
} else {
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read bytes until new line delimiter
|
||||
pub fn readline(&mut self) -> Option<Bytes> {
|
||||
pub fn readline(&mut self) -> Result<Option<Bytes>, MultipartError> {
|
||||
self.read_until(b"\n")
|
||||
}
|
||||
|
||||
@ -980,7 +1001,7 @@ mod tests {
|
||||
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
payload.poll_stream().unwrap();
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert_eq!(None, payload.read_max(1).unwrap());
|
||||
})
|
||||
}
|
||||
|
||||
@ -990,14 +1011,14 @@ mod tests {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
|
||||
assert_eq!(None, payload.read_max(4));
|
||||
assert_eq!(None, payload.read_max(4).unwrap());
|
||||
sender.feed_data(Bytes::from("data"));
|
||||
sender.feed_eof();
|
||||
payload.poll_stream().unwrap();
|
||||
|
||||
assert_eq!(Some(Bytes::from("data")), payload.read_max(4));
|
||||
assert_eq!(Some(Bytes::from("data")), payload.read_max(4).unwrap());
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert!(payload.read_max(1).is_err());
|
||||
assert!(payload.eof);
|
||||
})
|
||||
}
|
||||
@ -1007,7 +1028,7 @@ mod tests {
|
||||
run_on(|| {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
assert_eq!(None, payload.read_max(1));
|
||||
assert_eq!(None, payload.read_max(1).unwrap());
|
||||
sender.set_error(PayloadError::Incomplete(None));
|
||||
payload.poll_stream().err().unwrap();
|
||||
})
|
||||
@ -1024,10 +1045,10 @@ mod tests {
|
||||
payload.poll_stream().unwrap();
|
||||
assert_eq!(payload.buf.len(), 10);
|
||||
|
||||
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5));
|
||||
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5).unwrap());
|
||||
assert_eq!(payload.buf.len(), 5);
|
||||
|
||||
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5));
|
||||
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap());
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
})
|
||||
}
|
||||
@ -1058,16 +1079,22 @@ mod tests {
|
||||
let (mut sender, payload) = Payload::create(false);
|
||||
let mut payload = PayloadBuffer::new(payload);
|
||||
|
||||
assert_eq!(None, payload.read_until(b"ne"));
|
||||
assert_eq!(None, payload.read_until(b"ne").unwrap());
|
||||
|
||||
sender.feed_data(Bytes::from("line1"));
|
||||
sender.feed_data(Bytes::from("line2"));
|
||||
payload.poll_stream().unwrap();
|
||||
|
||||
assert_eq!(Some(Bytes::from("line")), payload.read_until(b"ne"));
|
||||
assert_eq!(
|
||||
Some(Bytes::from("line")),
|
||||
payload.read_until(b"ne").unwrap()
|
||||
);
|
||||
assert_eq!(payload.buf.len(), 6);
|
||||
|
||||
assert_eq!(Some(Bytes::from("1line2")), payload.read_until(b"2"));
|
||||
assert_eq!(
|
||||
Some(Bytes::from("1line2")),
|
||||
payload.read_until(b"2").unwrap()
|
||||
);
|
||||
assert_eq!(payload.buf.len(), 0);
|
||||
})
|
||||
}
|
||||
|
@ -1,5 +1,17 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2019-06-03
|
||||
|
||||
* Fix optional cookie session support
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Use actix-web 1.0.0-rc
|
||||
|
||||
## [0.1.0-beta.4] - 2019-05-12
|
||||
|
||||
* Use actix-web 1.0.0-beta.4
|
||||
|
||||
## [0.1.0-beta.2] - 2019-04-28
|
||||
|
||||
* Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-session"
|
||||
version = "0.1.0-beta.2"
|
||||
version = "0.1.1"
|
||||
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-beta.2"
|
||||
actix-service = "0.3.4"
|
||||
actix-web = "1.0.0-rc"
|
||||
actix-service = "0.4.0"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.2.2"
|
||||
hashbrown = "0.3.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
time = "0.1.42"
|
||||
|
1
actix-session/LICENSE-APACHE
Symbolic link
1
actix-session/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-session/LICENSE-MIT
Symbolic link
1
actix-session/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -52,7 +52,9 @@ use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
|
||||
#[cfg(feature = "cookie-session")]
|
||||
mod cookie;
|
||||
#[cfg(feature = "cookie-session")]
|
||||
pub use crate::cookie::CookieSession;
|
||||
|
||||
/// The high-level interface you use to modify session data.
|
||||
|
@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.0] - 2019-05-29
|
||||
|
||||
* Update actix-http and actix-web
|
||||
|
||||
## [0.1.0-alpha.3] - 2019-04-02
|
||||
|
||||
* Update actix-http and actix-web
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-actors"
|
||||
version = "1.0.0-alpha.3"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix actors support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -18,13 +18,13 @@ name = "actix_web_actors"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.8.0"
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-http = "0.1.1"
|
||||
actix = "0.8.3"
|
||||
actix-web = "1.0.0-rc"
|
||||
actix-http = "0.2.2"
|
||||
actix-codec = "0.1.2"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.6"
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
|
1
actix-web-actors/LICENSE-APACHE
Symbolic link
1
actix-web-actors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-web-actors/LICENSE-MIT
Symbolic link
1
actix-web-actors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -1,5 +1,17 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.2] - 2019-06-04
|
||||
|
||||
* Add macros for head, options, trace, connect and patch http methods
|
||||
|
||||
## [0.1.1] - 2019-06-01
|
||||
|
||||
* Add syn "extra-traits" feature
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Release
|
||||
|
||||
## [0.1.0-beta.1] - 2019-04-20
|
||||
|
||||
* Gen code for actix-web 1.0.0-beta.1
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-codegen"
|
||||
version = "0.1.0-beta.1"
|
||||
version = "0.1.2"
|
||||
description = "Actix web proc macros"
|
||||
readme = "README.md"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
@ -12,11 +12,11 @@ workspace = ".."
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
quote = "0.6"
|
||||
syn = { version = "0.15", features = ["full", "parsing"] }
|
||||
quote = "0.6.12"
|
||||
syn = { version = "0.15.34", features = ["full", "parsing", "extra-traits"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-alpha.6" }
|
||||
actix-http = { version = "0.1.1", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.0", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0-rc" }
|
||||
actix-http = { version = "0.2.2", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
futures = { version = "0.1" }
|
||||
|
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
1
actix-web-codegen/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-web-codegen/LICENSE-MIT
Symbolic link
1
actix-web-codegen/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -11,6 +11,11 @@
|
||||
//! - [post](attr.post.html)
|
||||
//! - [put](attr.put.html)
|
||||
//! - [delete](attr.delete.html)
|
||||
//! - [head](attr.head.html)
|
||||
//! - [connect](attr.connect.html)
|
||||
//! - [options](attr.options.html)
|
||||
//! - [trace](attr.trace.html)
|
||||
//! - [patch](attr.patch.html)
|
||||
//!
|
||||
//! ### Attributes:
|
||||
//!
|
||||
@ -92,3 +97,63 @@ pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Delete);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `HEAD` method guard.
|
||||
///
|
||||
/// Syntax: `#[head("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [head](attr.head.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn head(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Head);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `CONNECT` method guard.
|
||||
///
|
||||
/// Syntax: `#[connect("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [connect](attr.connect.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn connect(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Connect);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `OPTIONS` method guard.
|
||||
///
|
||||
/// Syntax: `#[options("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [options](attr.options.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn options(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Options);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `TRACE` method guard.
|
||||
///
|
||||
/// Syntax: `#[trace("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [trace](attr.trace.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn trace(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Trace);
|
||||
gen.generate()
|
||||
}
|
||||
|
||||
/// Creates route handler with `PATCH` method guard.
|
||||
///
|
||||
/// Syntax: `#[patch("path"[, attributes])]`
|
||||
///
|
||||
/// Attributes are the same as in [patch](attr.patch.html)
|
||||
#[proc_macro_attribute]
|
||||
pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let args = parse_macro_input!(args as syn::AttributeArgs);
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Patch);
|
||||
gen.generate()
|
||||
}
|
||||
|
@ -25,6 +25,11 @@ pub enum GuardType {
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Head,
|
||||
Connect,
|
||||
Options,
|
||||
Trace,
|
||||
Patch,
|
||||
}
|
||||
|
||||
impl fmt::Display for GuardType {
|
||||
@ -34,6 +39,11 @@ impl fmt::Display for GuardType {
|
||||
&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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_web::{http, App, HttpResponse, Responder};
|
||||
use actix_web_codegen::{get, post, put};
|
||||
use actix_web::{http, web::Path, App, HttpResponse, Responder};
|
||||
use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
|
||||
use futures::{future, Future};
|
||||
|
||||
#[get("/test")]
|
||||
@ -14,11 +14,36 @@ fn put_test() -> impl Responder {
|
||||
HttpResponse::Created()
|
||||
}
|
||||
|
||||
#[patch("/test")]
|
||||
fn patch_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[post("/test")]
|
||||
fn post_test() -> impl Responder {
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[head("/test")]
|
||||
fn head_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[connect("/test")]
|
||||
fn connect_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[options("/test")]
|
||||
fn options_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[trace("/test")]
|
||||
fn trace_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[get("/test")]
|
||||
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
@ -29,6 +54,45 @@ fn auto_sync() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
}
|
||||
|
||||
#[put("/test/{param}")]
|
||||
fn put_param_test(_: Path<String>) -> impl Responder {
|
||||
HttpResponse::Created()
|
||||
}
|
||||
|
||||
#[delete("/test/{param}")]
|
||||
fn delete_param_test(_: Path<String>) -> impl Responder {
|
||||
HttpResponse::NoContent()
|
||||
}
|
||||
|
||||
#[get("/test/{param}")]
|
||||
fn get_param_test(_: Path<String>) -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_params() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
HttpService::new(
|
||||
App::new()
|
||||
.service(get_param_test)
|
||||
.service(put_param_test)
|
||||
.service(delete_param_test),
|
||||
)
|
||||
});
|
||||
|
||||
let request = srv.request(http::Method::GET, srv.url("/test/it"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::OK);
|
||||
|
||||
let request = srv.request(http::Method::PUT, srv.url("/test/it"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::CREATED);
|
||||
|
||||
let request = srv.request(http::Method::DELETE, srv.url("/test/it"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert_eq!(response.status(), http::StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_body() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
@ -36,6 +100,11 @@ fn test_body() {
|
||||
App::new()
|
||||
.service(post_test)
|
||||
.service(put_test)
|
||||
.service(head_test)
|
||||
.service(connect_test)
|
||||
.service(options_test)
|
||||
.service(trace_test)
|
||||
.service(patch_test)
|
||||
.service(test),
|
||||
)
|
||||
});
|
||||
@ -43,6 +112,26 @@ fn test_body() {
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::HEAD, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::CONNECT, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::OPTIONS, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::TRACE, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::PATCH, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
let request = srv.request(http::Method::PUT, srv.url("/test"));
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
@ -1,9 +1,21 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-06-05
|
||||
|
||||
### Added
|
||||
|
||||
* Add license files
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Added
|
||||
|
||||
* Allow to send headers in `Camel-Case` form.
|
||||
|
||||
### Changed
|
||||
|
||||
* Upgrade actix-http dependency.
|
||||
|
||||
|
||||
## [0.1.1] - 2019-04-19
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "0.1.1"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http client."
|
||||
readme = "README.md"
|
||||
@ -40,8 +40,8 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-http = "0.1.4"
|
||||
actix-service = "0.4.0"
|
||||
actix-http = "0.2.3"
|
||||
base64 = "0.10.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
@ -58,11 +58,11 @@ openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-web = { version = "1.0.0-beta.1", features=["ssl"] }
|
||||
actix-http = { version = "0.1.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.1.1", features=["ssl"] }
|
||||
actix-utils = "0.3.4"
|
||||
actix-server = { version = "0.4.3", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0-rc", features=["ssl"] }
|
||||
actix-http = { version = "0.2.3", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.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"
|
||||
|
1
awc/LICENSE-APACHE
Symbolic link
1
awc/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
awc/LICENSE-MIT
Symbolic link
1
awc/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -140,51 +140,46 @@ impl ClientBuilder {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test;
|
||||
|
||||
#[test]
|
||||
fn client_basic_auth() {
|
||||
test::run_on(|| {
|
||||
let client = ClientBuilder::new().basic_auth("username", Some("password"));
|
||||
assert_eq!(
|
||||
client
|
||||
.config
|
||||
.headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU6cGFzc3dvcmQ="
|
||||
);
|
||||
let client = ClientBuilder::new().basic_auth("username", Some("password"));
|
||||
assert_eq!(
|
||||
client
|
||||
.config
|
||||
.headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU6cGFzc3dvcmQ="
|
||||
);
|
||||
|
||||
let client = ClientBuilder::new().basic_auth("username", None);
|
||||
assert_eq!(
|
||||
client
|
||||
.config
|
||||
.headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU="
|
||||
);
|
||||
});
|
||||
let client = ClientBuilder::new().basic_auth("username", None);
|
||||
assert_eq!(
|
||||
client
|
||||
.config
|
||||
.headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Basic dXNlcm5hbWU="
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_bearer_auth() {
|
||||
test::run_on(|| {
|
||||
let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n");
|
||||
assert_eq!(
|
||||
client
|
||||
.config
|
||||
.headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Bearer someS3cr3tAutht0k3n"
|
||||
);
|
||||
})
|
||||
let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n");
|
||||
assert_eq!(
|
||||
client
|
||||
.config
|
||||
.headers
|
||||
.get(header::AUTHORIZATION)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
"Bearer someS3cr3tAutht0k3n"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -38,6 +38,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};
|
||||
|
||||
|
@ -347,10 +347,11 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use actix_http_test::block_on;
|
||||
use futures::Async;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{http::header, test::block_on, test::TestResponse};
|
||||
use crate::{http::header, test::TestResponse};
|
||||
|
||||
#[test]
|
||||
fn test_body() {
|
||||
|
@ -6,39 +6,10 @@ use actix_http::http::header::{self, Header, HeaderValue, IntoHeaderValue};
|
||||
use actix_http::http::{HeaderName, HttpTryFrom, StatusCode, Version};
|
||||
use actix_http::{h1, Payload, ResponseHead};
|
||||
use bytes::Bytes;
|
||||
#[cfg(test)]
|
||||
use futures::Future;
|
||||
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
|
||||
|
||||
use crate::ClientResponse;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static RT: std::cell::RefCell<actix_rt::Runtime> = {
|
||||
std::cell::RefCell::new(actix_rt::Runtime::new().unwrap())
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn run_on<F, R>(f: F) -> R
|
||||
where
|
||||
F: Fn() -> R,
|
||||
{
|
||||
RT.with(move |rt| {
|
||||
rt.borrow_mut()
|
||||
.block_on(futures::future::lazy(|| Ok::<_, ()>(f())))
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn block_on<F>(f: F) -> Result<F::Item, F::Error>
|
||||
where
|
||||
F: Future,
|
||||
{
|
||||
RT.with(move |rt| rt.borrow_mut().block_on(f))
|
||||
}
|
||||
|
||||
/// Test `ClientResponse` builder
|
||||
pub struct TestResponse {
|
||||
head: ResponseHead,
|
||||
|
@ -318,7 +318,9 @@ impl WebsocketsRequest {
|
||||
}
|
||||
} else {
|
||||
log::trace!("Invalid connection header: {:?}", conn);
|
||||
return Err(WsClientError::InvalidConnectionHeader(conn.clone()));
|
||||
return Err(WsClientError::InvalidConnectionHeader(
|
||||
conn.clone(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
log::trace!("Missing connection header");
|
||||
@ -462,29 +464,28 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn basics() {
|
||||
actix_http_test::run_on(|| {
|
||||
let req = Client::new()
|
||||
.ws("http://localhost/")
|
||||
.origin("test-origin")
|
||||
.max_frame_size(100)
|
||||
.server_mode()
|
||||
.protocols(&["v1", "v2"])
|
||||
.set_header_if_none(header::CONTENT_TYPE, "json")
|
||||
.set_header_if_none(header::CONTENT_TYPE, "text")
|
||||
.cookie(Cookie::build("cookie1", "value1").finish());
|
||||
assert_eq!(
|
||||
req.origin.as_ref().unwrap().to_str().unwrap(),
|
||||
"test-origin"
|
||||
);
|
||||
assert_eq!(req.max_size, 100);
|
||||
assert_eq!(req.server_mode, true);
|
||||
assert_eq!(req.protocols, Some("v1,v2".to_string()));
|
||||
assert_eq!(
|
||||
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
|
||||
header::HeaderValue::from_static("json")
|
||||
);
|
||||
let _ = req.connect();
|
||||
});
|
||||
let req = Client::new()
|
||||
.ws("http://localhost/")
|
||||
.origin("test-origin")
|
||||
.max_frame_size(100)
|
||||
.server_mode()
|
||||
.protocols(&["v1", "v2"])
|
||||
.set_header_if_none(header::CONTENT_TYPE, "json")
|
||||
.set_header_if_none(header::CONTENT_TYPE, "text")
|
||||
.cookie(Cookie::build("cookie1", "value1").finish());
|
||||
assert_eq!(
|
||||
req.origin.as_ref().unwrap().to_str().unwrap(),
|
||||
"test-origin"
|
||||
);
|
||||
assert_eq!(req.max_size, 100);
|
||||
assert_eq!(req.server_mode, true);
|
||||
assert_eq!(req.protocols, Some("v1,v2".to_string()));
|
||||
assert_eq!(
|
||||
req.head.headers.get(header::CONTENT_TYPE).unwrap(),
|
||||
header::HeaderValue::from_static("json")
|
||||
);
|
||||
|
||||
let _ = actix_http_test::block_fn(move || req.connect());
|
||||
|
||||
assert!(Client::new().ws("/").connect().poll().is_err());
|
||||
assert!(Client::new().ws("http:///test").connect().poll().is_err());
|
||||
|
@ -15,7 +15,7 @@ use rand::Rng;
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
use actix_service::{fn_service, NewService};
|
||||
use actix_service::{service_fn, NewService};
|
||||
use actix_web::http::{Cookie, Version};
|
||||
use actix_web::middleware::{BodyEncoding, Compress};
|
||||
use actix_web::{http::header, web, App, Error, HttpMessage, HttpRequest, HttpResponse};
|
||||
@ -182,7 +182,7 @@ fn test_connection_reuse() {
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
@ -216,7 +216,7 @@ fn test_connection_reuse_h2() {
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
@ -268,7 +268,7 @@ fn test_connection_force_close() {
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
@ -300,7 +300,7 @@ fn test_connection_server_close() {
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
@ -335,7 +335,7 @@ fn test_connection_wait_queue() {
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
@ -380,7 +380,7 @@ fn test_connection_wait_queue_force_close() {
|
||||
|
||||
let mut srv = TestServer::new(move || {
|
||||
let num2 = num2.clone();
|
||||
fn_service(move |io| {
|
||||
service_fn(move |io| {
|
||||
num2.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(io)
|
||||
})
|
||||
|
@ -1,17 +1,11 @@
|
||||
use std::io;
|
||||
|
||||
use actix_codec::Framed;
|
||||
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
|
||||
use actix_http_test::TestServer;
|
||||
use actix_server::Io;
|
||||
use actix_service::{fn_service, NewService};
|
||||
use actix_utils::framed::IntoFramed;
|
||||
use actix_utils::stream::TakeItem;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{ok, Either};
|
||||
use futures::future::ok;
|
||||
use futures::{Future, Sink, Stream};
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
use actix_http::{body::BodySize, h1, ws, Request, ResponseError, ServiceConfig};
|
||||
|
||||
fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Error> {
|
||||
match req {
|
||||
@ -37,52 +31,20 @@ fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Err
|
||||
#[test]
|
||||
fn test_simple() {
|
||||
let mut srv = TestServer::new(|| {
|
||||
fn_service(|io: Io<TcpStream>| Ok(io.into_parts().0))
|
||||
.and_then(IntoFramed::new(|| h1::Codec::new(ServiceConfig::default())))
|
||||
.and_then(TakeItem::new().map_err(|_| ()))
|
||||
.and_then(
|
||||
|(req, framed): (Option<h1::Message<Request>>, Framed<_, _>)| {
|
||||
// validate request
|
||||
if let Some(h1::Message::Item(req)) = req {
|
||||
match ws::verify_handshake(req.head()) {
|
||||
Err(e) => {
|
||||
// validation failed
|
||||
let res = e.error_response();
|
||||
Either::A(
|
||||
framed
|
||||
.send(h1::Message::Item((
|
||||
res.drop_body(),
|
||||
BodySize::Empty,
|
||||
)))
|
||||
.map_err(|_| ())
|
||||
.map(|_| ()),
|
||||
)
|
||||
}
|
||||
Ok(_) => {
|
||||
let res = ws::handshake_response(req.head()).finish();
|
||||
Either::B(
|
||||
// send handshake response
|
||||
framed
|
||||
.send(h1::Message::Item((
|
||||
res.drop_body(),
|
||||
BodySize::None,
|
||||
)))
|
||||
.map_err(|_| ())
|
||||
.and_then(|framed| {
|
||||
// start websocket service
|
||||
let framed =
|
||||
framed.into_framed(ws::Codec::new());
|
||||
ws::Transport::with(framed, ws_service)
|
||||
.map_err(|_| ())
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
},
|
||||
)
|
||||
HttpService::build()
|
||||
.upgrade(|(req, framed): (Request, Framed<_, _>)| {
|
||||
let res = ws::handshake_response(req.head()).finish();
|
||||
// send handshake response
|
||||
framed
|
||||
.send(h1::Message::Item((res.drop_body(), BodySize::None)))
|
||||
.map_err(|e: io::Error| e.into())
|
||||
.and_then(|framed| {
|
||||
// start websocket service
|
||||
let framed = framed.into_framed(ws::Codec::new());
|
||||
ws::Transport::with(framed, ws_service)
|
||||
})
|
||||
})
|
||||
.finish(|_| ok::<_, Error>(Response::NotFound()))
|
||||
});
|
||||
|
||||
// client service
|
||||
|
21
src/app.rs
21
src/app.rs
@ -4,7 +4,6 @@ use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::body::{Body, MessageBody};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::boxed::{self, BoxedNewService};
|
||||
use actix_service::{
|
||||
apply_transform, IntoNewService, IntoTransform, NewService, Transform,
|
||||
@ -59,6 +58,7 @@ impl<T, B> App<T, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
@ -95,8 +95,15 @@ where
|
||||
/// web::get().to(index)));
|
||||
/// }
|
||||
/// ```
|
||||
pub fn data<U: Into<Data<U>> + 'static>(mut self, data: U) -> Self {
|
||||
self.data.push(Box::new(data.into()));
|
||||
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||
self.data.push(Box::new(Data::new(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
|
||||
}
|
||||
|
||||
@ -128,7 +135,7 @@ where
|
||||
/// ```
|
||||
pub fn configure<F>(mut self, f: F) -> Self
|
||||
where
|
||||
F: Fn(&mut ServiceConfig),
|
||||
F: FnOnce(&mut ServiceConfig),
|
||||
{
|
||||
let mut cfg = ServiceConfig::new();
|
||||
f(&mut cfg);
|
||||
@ -234,6 +241,7 @@ where
|
||||
where
|
||||
F: IntoNewService<U>,
|
||||
U: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -319,6 +327,7 @@ where
|
||||
mw: F,
|
||||
) -> App<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B1>,
|
||||
Error = Error,
|
||||
@ -384,6 +393,7 @@ where
|
||||
mw: F,
|
||||
) -> App<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B1>,
|
||||
Error = Error,
|
||||
@ -400,10 +410,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, B> IntoNewService<AppInit<T, B>, ServerConfig> for App<T, B>
|
||||
impl<T, B> IntoNewService<AppInit<T, B>> for App<T, B>
|
||||
where
|
||||
B: MessageBody,
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
|
@ -6,7 +6,7 @@ use actix_http::{Extensions, Request, Response};
|
||||
use actix_router::{Path, ResourceDef, ResourceInfo, Router, Url};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||
use actix_service::{fn_service, NewService, Service};
|
||||
use actix_service::{service_fn, NewService, Service};
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
@ -31,6 +31,7 @@ type BoxedResponse = Either<
|
||||
pub struct AppInit<T, B>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
@ -46,15 +47,17 @@ where
|
||||
pub(crate) external: RefCell<Vec<ResourceDef>>,
|
||||
}
|
||||
|
||||
impl<T, B> NewService<ServerConfig> for AppInit<T, B>
|
||||
impl<T, B> NewService for AppInit<T, B>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
InitError = (),
|
||||
>,
|
||||
{
|
||||
type Config = ServerConfig;
|
||||
type Request = Request;
|
||||
type Response = ServiceResponse<B>;
|
||||
type Error = T::Error;
|
||||
@ -65,7 +68,7 @@ where
|
||||
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
||||
// update resource default service
|
||||
let default = self.default.clone().unwrap_or_else(|| {
|
||||
Rc::new(boxed::new_service(fn_service(|req: ServiceRequest| {
|
||||
Rc::new(boxed::new_service(service_fn(|req: ServiceRequest| {
|
||||
Ok(req.into_response(Response::NotFound().finish()))
|
||||
})))
|
||||
});
|
||||
@ -148,6 +151,7 @@ where
|
||||
impl<T, B> Future for AppInitResult<T, B>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = Error,
|
||||
@ -179,7 +183,7 @@ where
|
||||
}
|
||||
|
||||
/// Service to convert `Request` to a `ServiceRequest<S>`
|
||||
pub struct AppInitService<T: Service, B>
|
||||
pub struct AppInitService<T, B>
|
||||
where
|
||||
T: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
@ -211,19 +215,30 @@ where
|
||||
inner.path.get_mut().update(&head.uri);
|
||||
inner.path.reset();
|
||||
inner.head = head;
|
||||
inner.payload = payload;
|
||||
inner.app_data = self.data.clone();
|
||||
req
|
||||
} else {
|
||||
HttpRequest::new(
|
||||
Path::new(Url::new(head.uri.clone())),
|
||||
head,
|
||||
payload,
|
||||
self.rmap.clone(),
|
||||
self.config.clone(),
|
||||
self.data.clone(),
|
||||
self.pool,
|
||||
)
|
||||
};
|
||||
self.service.call(ServiceRequest::from_parts(req, payload))
|
||||
self.service.call(ServiceRequest::new(req))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, B> Drop for AppInitService<T, B>
|
||||
where
|
||||
T: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
self.pool.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@ -233,6 +248,7 @@ pub struct AppRoutingFactory {
|
||||
}
|
||||
|
||||
impl NewService for AppRoutingFactory {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -391,6 +407,7 @@ impl AppEntry {
|
||||
}
|
||||
|
||||
impl NewService for AppEntry {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -402,3 +419,37 @@ impl NewService for AppEntry {
|
||||
self.factory.borrow_mut().as_mut().unwrap().new_service(&())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use crate::{test, web, App, HttpResponse};
|
||||
|
||||
struct DropData(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for DropData {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_data() {
|
||||
let data = Arc::new(AtomicBool::new(false));
|
||||
{
|
||||
let mut app = test::init_service(
|
||||
App::new()
|
||||
.data(DropData(data.clone()))
|
||||
.service(web::resource("/test").to(|| HttpResponse::Ok())),
|
||||
);
|
||||
let req = test::TestRequest::with_uri("/test").to_request();
|
||||
let _ = test::block_on(app.call(req)).unwrap();
|
||||
}
|
||||
assert!(data.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
|
@ -31,7 +31,7 @@ pub struct AppService {
|
||||
Option<Guards>,
|
||||
Option<Rc<ResourceMap>>,
|
||||
)>,
|
||||
route_data: Rc<Vec<Box<DataFactory>>>,
|
||||
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||
}
|
||||
|
||||
impl AppService {
|
||||
@ -39,12 +39,12 @@ impl AppService {
|
||||
pub(crate) fn new(
|
||||
config: AppConfig,
|
||||
default: Rc<HttpNewService>,
|
||||
route_data: Rc<Vec<Box<DataFactory>>>,
|
||||
service_data: Rc<Vec<Box<DataFactory>>>,
|
||||
) -> Self {
|
||||
AppService {
|
||||
config,
|
||||
default,
|
||||
route_data,
|
||||
service_data,
|
||||
root: true,
|
||||
services: Vec::new(),
|
||||
}
|
||||
@ -75,7 +75,7 @@ impl AppService {
|
||||
default: self.default.clone(),
|
||||
services: Vec::new(),
|
||||
root: false,
|
||||
route_data: self.route_data.clone(),
|
||||
service_data: self.service_data.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@ -90,11 +90,11 @@ impl AppService {
|
||||
}
|
||||
|
||||
/// Set global route data
|
||||
pub fn set_route_data(&self, extensions: &mut Extensions) -> bool {
|
||||
for f in self.route_data.iter() {
|
||||
pub fn set_service_data(&self, extensions: &mut Extensions) -> bool {
|
||||
for f in self.service_data.iter() {
|
||||
f.create(extensions);
|
||||
}
|
||||
!self.route_data.is_empty()
|
||||
!self.service_data.is_empty()
|
||||
}
|
||||
|
||||
/// Register http service
|
||||
@ -107,6 +107,7 @@ impl AppService {
|
||||
) where
|
||||
F: IntoNewService<S>,
|
||||
S: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -187,12 +188,12 @@ impl ServiceConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set application data. Applicatin data could be accessed
|
||||
/// Set application data. Application data could be accessed
|
||||
/// by using `Data<T>` extractor where `T` is data type.
|
||||
///
|
||||
/// This is same as `App::data()` method.
|
||||
pub fn data<S: Into<Data<S>> + 'static>(&mut self, data: S) -> &mut Self {
|
||||
self.data.push(Box::new(data.into()));
|
||||
pub fn data<S: 'static>(&mut self, data: S) -> &mut Self {
|
||||
self.data.push(Box::new(Data::new(data)));
|
||||
self
|
||||
}
|
||||
|
||||
|
29
src/data.rs
29
src/data.rs
@ -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)));
|
||||
@ -93,12 +93,6 @@ impl<T> Clone for Data<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for Data<T> {
|
||||
fn from(data: T) -> Self {
|
||||
Data::new(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> FromRequest for Data<T> {
|
||||
type Config = ();
|
||||
type Error = Error;
|
||||
@ -136,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};
|
||||
@ -160,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 =
|
||||
|
46
src/error.rs
46
src/error.rs
@ -6,6 +6,7 @@ use url::ParseError as UrlParseError;
|
||||
|
||||
use crate::http::StatusCode;
|
||||
use crate::HttpResponse;
|
||||
use serde_urlencoded::de;
|
||||
|
||||
/// Errors which can occur when attempting to generate resource uri.
|
||||
#[derive(Debug, PartialEq, Display, From)]
|
||||
@ -91,6 +92,42 @@ 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 {
|
||||
/// Deserialize error
|
||||
#[display(fmt = "Query deserialize error: {}", _0)]
|
||||
Deserialize(de::Error),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `QueryPayloadError`
|
||||
impl ResponseError for QueryPayloadError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
QueryPayloadError::Deserialize(_) => {
|
||||
HttpResponse::new(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Error type returned when reading body as lines.
|
||||
#[derive(From, Display, Debug)]
|
||||
pub enum ReadlinesError {
|
||||
@ -143,6 +180,15 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_query_payload_error() {
|
||||
let resp: HttpResponse = QueryPayloadError::Deserialize(
|
||||
serde_urlencoded::from_str::<i32>("bad query").unwrap_err(),
|
||||
)
|
||||
.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_readlines_error() {
|
||||
let resp: HttpResponse = ReadlinesError::LimitOverflow.error_response();
|
||||
|
@ -1,7 +1,8 @@
|
||||
use std::convert::Infallible;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use actix_http::{Error, Payload, Response};
|
||||
use actix_service::{NewService, Service, Void};
|
||||
use actix_http::{Error, Response};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
|
||||
@ -71,7 +72,7 @@ where
|
||||
{
|
||||
type Request = (T, HttpRequest);
|
||||
type Response = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
type Future = HandlerServiceResponse<<R::Future as IntoFuture>::Future>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -98,7 +99,7 @@ where
|
||||
T::Error: Into<Error>,
|
||||
{
|
||||
type Item = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll() {
|
||||
@ -191,7 +192,7 @@ where
|
||||
{
|
||||
type Request = (T, HttpRequest);
|
||||
type Response = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
type Future = AsyncHandlerServiceResponse<R::Future>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@ -225,7 +226,7 @@ where
|
||||
T::Error: Into<Error>,
|
||||
{
|
||||
type Item = ServiceResponse;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut2 {
|
||||
@ -280,9 +281,13 @@ impl<T: FromRequest, S> Extract<T, S> {
|
||||
|
||||
impl<T: FromRequest, S> NewService for Extract<T, S>
|
||||
where
|
||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>
|
||||
+ Clone,
|
||||
S: Service<
|
||||
Request = (T, HttpRequest),
|
||||
Response = ServiceResponse,
|
||||
Error = Infallible,
|
||||
> + Clone,
|
||||
{
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = (Error, ServiceRequest);
|
||||
@ -305,8 +310,11 @@ pub struct ExtractService<T: FromRequest, S> {
|
||||
|
||||
impl<T: FromRequest, S> Service for ExtractService<T, S>
|
||||
where
|
||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>
|
||||
+ Clone,
|
||||
S: Service<
|
||||
Request = (T, HttpRequest),
|
||||
Response = ServiceResponse,
|
||||
Error = Infallible,
|
||||
> + Clone,
|
||||
{
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
@ -323,15 +331,15 @@ where
|
||||
|
||||
ExtractResponse {
|
||||
fut,
|
||||
req,
|
||||
fut_s: None,
|
||||
req: Some((req, payload)),
|
||||
service: self.service.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExtractResponse<T: FromRequest, S: Service> {
|
||||
req: Option<(HttpRequest, Payload)>,
|
||||
req: HttpRequest,
|
||||
service: S,
|
||||
fut: <T::Future as IntoFuture>::Future,
|
||||
fut_s: Option<S::Future>,
|
||||
@ -339,7 +347,11 @@ pub struct ExtractResponse<T: FromRequest, S: Service> {
|
||||
|
||||
impl<T: FromRequest, S> Future for ExtractResponse<T, S>
|
||||
where
|
||||
S: Service<Request = (T, HttpRequest), Response = ServiceResponse, Error = Void>,
|
||||
S: Service<
|
||||
Request = (T, HttpRequest),
|
||||
Response = ServiceResponse,
|
||||
Error = Infallible,
|
||||
>,
|
||||
{
|
||||
type Item = ServiceResponse;
|
||||
type Error = (Error, ServiceRequest);
|
||||
@ -350,12 +362,11 @@ where
|
||||
}
|
||||
|
||||
let item = try_ready!(self.fut.poll().map_err(|e| {
|
||||
let (req, payload) = self.req.take().unwrap();
|
||||
let req = ServiceRequest::from_parts(req, payload);
|
||||
let req = ServiceRequest::new(self.req.clone());
|
||||
(e.into(), req)
|
||||
}));
|
||||
|
||||
self.fut_s = Some(self.service.call((item, self.req.take().unwrap().0)));
|
||||
self.fut_s = Some(self.service.call((item, self.req.clone())));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
|
11
src/lib.rs
11
src/lib.rs
@ -66,15 +66,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.
|
||||
//!
|
||||
@ -111,7 +111,7 @@ pub use actix_web_codegen::*;
|
||||
|
||||
// re-export for convenience
|
||||
pub use actix_http::Response as HttpResponse;
|
||||
pub use actix_http::{cookie, http, Error, HttpMessage, ResponseError, Result};
|
||||
pub use actix_http::{body, cookie, http, Error, HttpMessage, ResponseError, Result};
|
||||
|
||||
pub use crate::app::App;
|
||||
pub use crate::extract::FromRequest;
|
||||
@ -143,7 +143,7 @@ pub mod dev {
|
||||
pub use crate::types::json::JsonBody;
|
||||
pub use crate::types::readlines::Readlines;
|
||||
|
||||
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody};
|
||||
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
|
||||
pub use actix_http::encoding::Decoder as Decompress;
|
||||
pub use actix_http::ResponseBuilder as HttpResponseBuilder;
|
||||
pub use actix_http::{
|
||||
@ -151,6 +151,7 @@ pub mod dev {
|
||||
};
|
||||
pub use actix_router::{Path, ResourceDef, ResourcePath, Url};
|
||||
pub use actix_server::Server;
|
||||
pub use actix_service::{Service, Transform};
|
||||
|
||||
pub(crate) fn insert_slash(path: &str) -> String {
|
||||
let mut path = path.to_owned();
|
||||
|
@ -805,14 +805,15 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::{FnService, Transform};
|
||||
use actix_service::{IntoService, Transform};
|
||||
|
||||
use super::*;
|
||||
use crate::test::{self, block_on, TestRequest};
|
||||
|
||||
impl Cors {
|
||||
fn finish<S, B>(self, srv: S) -> CorsMiddleware<S>
|
||||
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
||||
where
|
||||
F: IntoService<S>,
|
||||
S: Service<
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse<B>,
|
||||
@ -822,7 +823,8 @@ mod tests {
|
||||
B: 'static,
|
||||
{
|
||||
block_on(
|
||||
IntoTransform::<CorsFactory, S>::into_transform(self).new_transform(srv),
|
||||
IntoTransform::<CorsFactory, S>::into_transform(self)
|
||||
.new_transform(srv.into_service()),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@ -1063,11 +1065,11 @@ mod tests {
|
||||
.allowed_headers(exposed_headers.clone())
|
||||
.expose_headers(exposed_headers.clone())
|
||||
.allowed_header(header::CONTENT_TYPE)
|
||||
.finish(FnService::new(move |req: ServiceRequest| {
|
||||
.finish(|req: ServiceRequest| {
|
||||
req.into_response(
|
||||
HttpResponse::Ok().header(header::VARY, "Accept").finish(),
|
||||
)
|
||||
}));
|
||||
});
|
||||
let req = TestRequest::with_header("Origin", "https://www.example.com")
|
||||
.method(Method::OPTIONS)
|
||||
.to_srv_request();
|
||||
|
@ -150,7 +150,7 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::FnService;
|
||||
use actix_service::IntoService;
|
||||
|
||||
use super::*;
|
||||
use crate::dev::ServiceRequest;
|
||||
@ -172,13 +172,13 @@ mod tests {
|
||||
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
|
||||
|
||||
let req = TestRequest::default().to_srv_request();
|
||||
let srv = FnService::new(|req: ServiceRequest| {
|
||||
let srv = |req: ServiceRequest| {
|
||||
req.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish())
|
||||
});
|
||||
};
|
||||
let mut mw = block_on(
|
||||
DefaultHeaders::new()
|
||||
.header(CONTENT_TYPE, "0001")
|
||||
.new_transform(srv),
|
||||
.new_transform(srv.into_service()),
|
||||
)
|
||||
.unwrap();
|
||||
let resp = block_on(mw.call(req)).unwrap();
|
||||
@ -187,11 +187,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_content_type() {
|
||||
let srv = FnService::new(|req: ServiceRequest| {
|
||||
req.into_response(HttpResponse::Ok().finish())
|
||||
});
|
||||
let mut mw =
|
||||
block_on(DefaultHeaders::new().content_type().new_transform(srv)).unwrap();
|
||||
let srv = |req: ServiceRequest| req.into_response(HttpResponse::Ok().finish());
|
||||
let mut mw = block_on(
|
||||
DefaultHeaders::new()
|
||||
.content_type()
|
||||
.new_transform(srv.into_service()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let req = TestRequest::default().to_srv_request();
|
||||
let resp = block_on(mw.call(req)).unwrap();
|
||||
|
@ -142,7 +142,7 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::FnService;
|
||||
use actix_service::IntoService;
|
||||
use futures::future::ok;
|
||||
|
||||
use super::*;
|
||||
@ -159,14 +159,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_handler() {
|
||||
let srv = FnService::new(|req: ServiceRequest| {
|
||||
let srv = |req: ServiceRequest| {
|
||||
req.into_response(HttpResponse::InternalServerError().finish())
|
||||
});
|
||||
};
|
||||
|
||||
let mut mw = test::block_on(
|
||||
ErrorHandlers::new()
|
||||
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500)
|
||||
.new_transform(srv),
|
||||
.new_transform(srv.into_service()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@ -185,14 +185,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_handler_async() {
|
||||
let srv = FnService::new(|req: ServiceRequest| {
|
||||
let srv = |req: ServiceRequest| {
|
||||
req.into_response(HttpResponse::InternalServerError().finish())
|
||||
});
|
||||
};
|
||||
|
||||
let mut mw = test::block_on(
|
||||
ErrorHandlers::new()
|
||||
.handler(StatusCode::INTERNAL_SERVER_ERROR, render_500_async)
|
||||
.new_transform(srv),
|
||||
.new_transform(srv.into_service()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
|
@ -53,7 +53,7 @@ use crate::HttpResponse;
|
||||
///
|
||||
/// `%a` Remote IP-address (IP-address of proxy if using reverse proxy)
|
||||
///
|
||||
/// `%t` Time when the request was started to process
|
||||
/// `%t` Time when the request was started to process (in rfc3339 format)
|
||||
///
|
||||
/// `%r` First line of request
|
||||
///
|
||||
@ -417,10 +417,7 @@ impl FormatText {
|
||||
}
|
||||
FormatText::UrlPath => *self = FormatText::Str(format!("{}", req.path())),
|
||||
FormatText::RequestTime => {
|
||||
*self = FormatText::Str(format!(
|
||||
"{:?}",
|
||||
now.strftime("[%d/%b/%Y:%H:%M:%S %z]").unwrap()
|
||||
))
|
||||
*self = FormatText::Str(format!("{}", now.rfc3339()))
|
||||
}
|
||||
FormatText::RequestHeader(ref name) => {
|
||||
let s = if let Some(val) = req.headers().get(name) {
|
||||
@ -457,7 +454,7 @@ impl<'a> fmt::Display for FormatDisplay<'a> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::{FnService, Service, Transform};
|
||||
use actix_service::{IntoService, Service, Transform};
|
||||
|
||||
use super::*;
|
||||
use crate::http::{header, StatusCode};
|
||||
@ -465,16 +462,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_logger() {
|
||||
let srv = FnService::new(|req: ServiceRequest| {
|
||||
let srv = |req: ServiceRequest| {
|
||||
req.into_response(
|
||||
HttpResponse::build(StatusCode::OK)
|
||||
.header("X-Test", "ttt")
|
||||
.finish(),
|
||||
)
|
||||
});
|
||||
};
|
||||
let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test");
|
||||
|
||||
let mut srv = block_on(logger.new_transform(srv)).unwrap();
|
||||
let mut srv = block_on(logger.new_transform(srv.into_service())).unwrap();
|
||||
|
||||
let req = TestRequest::with_header(
|
||||
header::USER_AGENT,
|
||||
@ -547,4 +544,29 @@ mod tests {
|
||||
assert!(s.contains("200 1024"));
|
||||
assert!(s.contains("ACTIX-WEB"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_time_format() {
|
||||
let mut format = Format::new("%t");
|
||||
let req = TestRequest::default().to_srv_request();
|
||||
|
||||
let now = time::now();
|
||||
for unit in &mut format.0 {
|
||||
unit.render_request(now, &req);
|
||||
}
|
||||
|
||||
let resp = HttpResponse::build(StatusCode::OK).force_close().finish();
|
||||
for unit in &mut format.0 {
|
||||
unit.render_response(&resp);
|
||||
}
|
||||
|
||||
let render = |fmt: &mut Formatter| {
|
||||
for unit in &format.0 {
|
||||
unit.render(fmt, 1024, now)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let s = format!("{}", FormatDisplay(&render));
|
||||
assert!(s.contains(&format!("{}", now.rfc3339())));
|
||||
}
|
||||
}
|
||||
|
@ -11,6 +11,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;
|
||||
|
@ -100,7 +100,7 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::FnService;
|
||||
use actix_service::IntoService;
|
||||
|
||||
use super::*;
|
||||
use crate::dev::ServiceRequest;
|
||||
@ -122,12 +122,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_in_place_normalization() {
|
||||
let srv = FnService::new(|req: ServiceRequest| {
|
||||
let srv = |req: ServiceRequest| {
|
||||
assert_eq!("/v1/something/", req.path());
|
||||
req.into_response(HttpResponse::Ok().finish())
|
||||
});
|
||||
};
|
||||
|
||||
let mut normalize = block_on(NormalizePath.new_transform(srv)).unwrap();
|
||||
let mut normalize =
|
||||
block_on(NormalizePath.new_transform(srv.into_service())).unwrap();
|
||||
|
||||
let req = TestRequest::with_uri("/v1//something////").to_srv_request();
|
||||
let res = block_on(normalize.call(req)).unwrap();
|
||||
@ -138,12 +139,13 @@ mod tests {
|
||||
fn should_normalize_nothing() {
|
||||
const URI: &str = "/v1/something/";
|
||||
|
||||
let srv = FnService::new(|req: ServiceRequest| {
|
||||
let srv = |req: ServiceRequest| {
|
||||
assert_eq!(URI, req.path());
|
||||
req.into_response(HttpResponse::Ok().finish())
|
||||
});
|
||||
};
|
||||
|
||||
let mut normalize = block_on(NormalizePath.new_transform(srv)).unwrap();
|
||||
let mut normalize =
|
||||
block_on(NormalizePath.new_transform(srv.into_service())).unwrap();
|
||||
|
||||
let req = TestRequest::with_uri(URI).to_srv_request();
|
||||
let res = block_on(normalize.call(req)).unwrap();
|
||||
|
@ -20,6 +20,7 @@ pub struct HttpRequest(pub(crate) Rc<HttpRequestInner>);
|
||||
pub(crate) struct HttpRequestInner {
|
||||
pub(crate) head: Message<RequestHead>,
|
||||
pub(crate) path: Path<Url>,
|
||||
pub(crate) payload: Payload,
|
||||
pub(crate) app_data: Rc<Extensions>,
|
||||
rmap: Rc<ResourceMap>,
|
||||
config: AppConfig,
|
||||
@ -31,6 +32,7 @@ impl HttpRequest {
|
||||
pub(crate) fn new(
|
||||
path: Path<Url>,
|
||||
head: Message<RequestHead>,
|
||||
payload: Payload,
|
||||
rmap: Rc<ResourceMap>,
|
||||
config: AppConfig,
|
||||
app_data: Rc<Extensions>,
|
||||
@ -39,6 +41,7 @@ impl HttpRequest {
|
||||
HttpRequest(Rc::new(HttpRequestInner {
|
||||
head,
|
||||
path,
|
||||
payload,
|
||||
rmap,
|
||||
config,
|
||||
app_data,
|
||||
@ -325,6 +328,10 @@ impl HttpRequestPool {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&self) {
|
||||
self.0.borrow_mut().clear()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -75,6 +75,7 @@ impl Resource {
|
||||
impl<T> Resource<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -274,6 +275,7 @@ where
|
||||
mw: F,
|
||||
) -> Resource<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -340,6 +342,7 @@ where
|
||||
mw: F,
|
||||
) -> Resource<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -360,6 +363,7 @@ where
|
||||
where
|
||||
F: IntoNewService<U>,
|
||||
U: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -380,6 +384,7 @@ where
|
||||
impl<T> HttpServiceFactory for Resource<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -402,7 +407,7 @@ where
|
||||
}
|
||||
// custom app data storage
|
||||
if let Some(ref mut ext) = self.data {
|
||||
config.set_route_data(ext);
|
||||
config.set_service_data(ext);
|
||||
}
|
||||
config.register_service(rdef, guards, self, None)
|
||||
}
|
||||
@ -411,6 +416,7 @@ where
|
||||
impl<T> IntoNewService<T> for Resource<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -435,6 +441,7 @@ pub struct ResourceFactory {
|
||||
}
|
||||
|
||||
impl NewService for ResourceFactory {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -575,6 +582,7 @@ impl ResourceEndpoint {
|
||||
}
|
||||
|
||||
impl NewService for ResourceEndpoint {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -598,7 +606,7 @@ mod tests {
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::test::{call_service, init_service, TestRequest};
|
||||
use crate::{web, App, Error, HttpResponse};
|
||||
use crate::{guard, web, App, Error, HttpResponse};
|
||||
|
||||
fn md<S, B>(
|
||||
req: ServiceRequest,
|
||||
@ -715,4 +723,45 @@ mod tests {
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resource_guards() {
|
||||
let mut srv = init_service(
|
||||
App::new()
|
||||
.service(
|
||||
web::resource("/test/{p}")
|
||||
.guard(guard::Get())
|
||||
.to(|| HttpResponse::Ok()),
|
||||
)
|
||||
.service(
|
||||
web::resource("/test/{p}")
|
||||
.guard(guard::Put())
|
||||
.to(|| HttpResponse::Created()),
|
||||
)
|
||||
.service(
|
||||
web::resource("/test/{p}")
|
||||
.guard(guard::Delete())
|
||||
.to(|| HttpResponse::NoContent()),
|
||||
),
|
||||
);
|
||||
|
||||
let req = TestRequest::with_uri("/test/it")
|
||||
.method(Method::GET)
|
||||
.to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/test/it")
|
||||
.method(Method::PUT)
|
||||
.to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
|
||||
let req = TestRequest::with_uri("/test/it")
|
||||
.method(Method::DELETE)
|
||||
.to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -122,7 +122,9 @@ impl ResourceMap {
|
||||
I: AsRef<str>,
|
||||
{
|
||||
if let Some(pattern) = self.named.get(name) {
|
||||
self.fill_root(path, elements)?;
|
||||
if pattern.pattern().starts_with("/") {
|
||||
self.fill_root(path, elements)?;
|
||||
}
|
||||
if pattern.resource_path(path, elements) {
|
||||
Ok(Some(()))
|
||||
} else {
|
||||
|
@ -26,6 +26,7 @@ type BoxedRouteService<Req, Res> = Box<
|
||||
|
||||
type BoxedRouteNewService<Req, Res> = Box<
|
||||
NewService<
|
||||
Config = (),
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Error,
|
||||
@ -61,6 +62,7 @@ impl Route {
|
||||
}
|
||||
|
||||
impl NewService for Route {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -283,6 +285,7 @@ where
|
||||
impl<T> RouteNewService<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = (Error, ServiceRequest),
|
||||
@ -299,6 +302,7 @@ where
|
||||
impl<T> NewService for RouteNewService<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = (Error, ServiceRequest),
|
||||
@ -307,6 +311,7 @@ where
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
|
199
src/scope.rs
199
src/scope.rs
@ -2,15 +2,17 @@ use std::cell::RefCell;
|
||||
use std::fmt;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::Response;
|
||||
use actix_http::{Extensions, Response};
|
||||
use actix_router::{ResourceDef, ResourceInfo, Router};
|
||||
use actix_service::boxed::{self, BoxedNewService, BoxedService};
|
||||
use actix_service::{
|
||||
ApplyTransform, IntoNewService, IntoTransform, NewService, Service, Transform,
|
||||
apply_transform, IntoNewService, IntoTransform, NewService, Service, Transform,
|
||||
};
|
||||
use futures::future::{ok, Either, Future, FutureResult};
|
||||
use futures::{Async, IntoFuture, Poll};
|
||||
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::data::Data;
|
||||
use crate::dev::{AppService, HttpServiceFactory};
|
||||
use crate::error::Error;
|
||||
use crate::guard::Guard;
|
||||
@ -61,9 +63,11 @@ type BoxedResponse = Either<
|
||||
pub struct Scope<T = ScopeEndpoint> {
|
||||
endpoint: T,
|
||||
rdef: String,
|
||||
data: Option<Extensions>,
|
||||
services: Vec<Box<ServiceFactory>>,
|
||||
guards: Vec<Box<Guard>>,
|
||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||
external: Vec<ResourceDef>,
|
||||
factory_ref: Rc<RefCell<Option<ScopeFactory>>>,
|
||||
}
|
||||
|
||||
@ -74,9 +78,11 @@ impl Scope {
|
||||
Scope {
|
||||
endpoint: ScopeEndpoint::new(fref.clone()),
|
||||
rdef: path.to_string(),
|
||||
data: None,
|
||||
guards: Vec::new(),
|
||||
services: Vec::new(),
|
||||
default: Rc::new(RefCell::new(None)),
|
||||
external: Vec::new(),
|
||||
factory_ref: fref,
|
||||
}
|
||||
}
|
||||
@ -85,6 +91,7 @@ impl Scope {
|
||||
impl<T> Scope<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -116,6 +123,89 @@ where
|
||||
self
|
||||
}
|
||||
|
||||
/// Set or override application data. Application data could be accessed
|
||||
/// by using `Data<T>` extractor where `T` is data type.
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::cell::Cell;
|
||||
/// use actix_web::{web, App};
|
||||
///
|
||||
/// struct MyData {
|
||||
/// counter: Cell<usize>,
|
||||
/// }
|
||||
///
|
||||
/// fn index(data: web::Data<MyData>) {
|
||||
/// data.counter.set(data.counter.get() + 1);
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::scope("/app")
|
||||
/// .data(MyData{ counter: Cell::new(0) })
|
||||
/// .service(
|
||||
/// web::resource("/index.html").route(
|
||||
/// web::get().to(index)))
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
pub fn data<U: 'static>(mut self, data: U) -> Self {
|
||||
if self.data.is_none() {
|
||||
self.data = Some(Extensions::new());
|
||||
}
|
||||
self.data.as_mut().unwrap().insert(Data::new(data));
|
||||
self
|
||||
}
|
||||
|
||||
/// Run external configuration as part of the scope building
|
||||
/// process
|
||||
///
|
||||
/// This function is useful for moving parts of configuration to a
|
||||
/// different module or even library. For example,
|
||||
/// some of the resource's configuration could be moved to different module.
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::{web, middleware, App, HttpResponse};
|
||||
///
|
||||
/// // this function could be located in different module
|
||||
/// fn config(cfg: &mut web::ServiceConfig) {
|
||||
/// cfg.service(web::resource("/test")
|
||||
/// .route(web::get().to(|| HttpResponse::Ok()))
|
||||
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
|
||||
/// );
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .wrap(middleware::Logger::default())
|
||||
/// .service(
|
||||
/// web::scope("/api")
|
||||
/// .configure(config)
|
||||
/// )
|
||||
/// .route("/index.html", web::get().to(|| HttpResponse::Ok()));
|
||||
/// }
|
||||
/// ```
|
||||
pub fn configure<F>(mut self, f: F) -> Self
|
||||
where
|
||||
F: FnOnce(&mut ServiceConfig),
|
||||
{
|
||||
let mut cfg = ServiceConfig::new();
|
||||
f(&mut cfg);
|
||||
self.services.extend(cfg.services);
|
||||
self.external.extend(cfg.external);
|
||||
|
||||
if !cfg.data.is_empty() {
|
||||
let mut data = self.data.unwrap_or_else(|| Extensions::new());
|
||||
|
||||
for value in cfg.data.iter() {
|
||||
value.create(&mut data);
|
||||
}
|
||||
|
||||
self.data = Some(data);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Register http service.
|
||||
///
|
||||
/// This is similar to `App's` service registration.
|
||||
@ -188,6 +278,7 @@ where
|
||||
where
|
||||
F: IntoNewService<U>,
|
||||
U: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -218,6 +309,7 @@ where
|
||||
mw: F,
|
||||
) -> Scope<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -234,13 +326,15 @@ where
|
||||
>,
|
||||
F: IntoTransform<M, T::Service>,
|
||||
{
|
||||
let endpoint = ApplyTransform::new(mw, self.endpoint);
|
||||
let endpoint = apply_transform(mw, self.endpoint);
|
||||
Scope {
|
||||
endpoint,
|
||||
rdef: self.rdef,
|
||||
data: self.data,
|
||||
guards: self.guards,
|
||||
services: self.services,
|
||||
default: self.default,
|
||||
external: self.external,
|
||||
factory_ref: self.factory_ref,
|
||||
}
|
||||
}
|
||||
@ -280,6 +374,7 @@ where
|
||||
mw: F,
|
||||
) -> Scope<
|
||||
impl NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -297,13 +392,14 @@ where
|
||||
impl<T> HttpServiceFactory for Scope<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
InitError = (),
|
||||
> + 'static,
|
||||
{
|
||||
fn register(self, config: &mut AppService) {
|
||||
fn register(mut self, config: &mut AppService) {
|
||||
// update default resource if needed
|
||||
if self.default.borrow().is_none() {
|
||||
*self.default.borrow_mut() = Some(config.default_service());
|
||||
@ -317,8 +413,19 @@ where
|
||||
|
||||
let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef));
|
||||
|
||||
// external resources
|
||||
for mut rdef in std::mem::replace(&mut self.external, Vec::new()) {
|
||||
rmap.add(&mut rdef, None);
|
||||
}
|
||||
|
||||
// custom app data storage
|
||||
if let Some(ref mut ext) = self.data {
|
||||
config.set_service_data(ext);
|
||||
}
|
||||
|
||||
// complete scope pipeline creation
|
||||
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
|
||||
data: self.data.take().map(|data| Rc::new(data)),
|
||||
default: self.default.clone(),
|
||||
services: Rc::new(
|
||||
cfg.into_services()
|
||||
@ -350,11 +457,13 @@ where
|
||||
}
|
||||
|
||||
pub struct ScopeFactory {
|
||||
data: Option<Rc<Extensions>>,
|
||||
services: Rc<Vec<(ResourceDef, HttpNewService, RefCell<Option<Guards>>)>>,
|
||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||
}
|
||||
|
||||
impl NewService for ScopeFactory {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -382,6 +491,7 @@ impl NewService for ScopeFactory {
|
||||
})
|
||||
.collect(),
|
||||
default: None,
|
||||
data: self.data.clone(),
|
||||
default_fut,
|
||||
}
|
||||
}
|
||||
@ -391,6 +501,7 @@ impl NewService for ScopeFactory {
|
||||
#[doc(hidden)]
|
||||
pub struct ScopeFactoryResponse {
|
||||
fut: Vec<CreateScopeServiceItem>,
|
||||
data: Option<Rc<Extensions>>,
|
||||
default: Option<HttpService>,
|
||||
default_fut: Option<Box<Future<Item = HttpService, Error = ()>>>,
|
||||
}
|
||||
@ -454,6 +565,7 @@ impl Future for ScopeFactoryResponse {
|
||||
router
|
||||
});
|
||||
Ok(Async::Ready(ScopeService {
|
||||
data: self.data.clone(),
|
||||
router: router.finish(),
|
||||
default: self.default.take(),
|
||||
_ready: None,
|
||||
@ -465,6 +577,7 @@ impl Future for ScopeFactoryResponse {
|
||||
}
|
||||
|
||||
pub struct ScopeService {
|
||||
data: Option<Rc<Extensions>>,
|
||||
router: Router<HttpService, Vec<Box<Guard>>>,
|
||||
default: Option<HttpService>,
|
||||
_ready: Option<(ServiceRequest, ResourceInfo)>,
|
||||
@ -493,6 +606,9 @@ impl Service for ScopeService {
|
||||
});
|
||||
|
||||
if let Some((srv, _info)) = res {
|
||||
if let Some(ref data) = self.data {
|
||||
req.set_data_container(data.clone());
|
||||
}
|
||||
Either::A(srv.call(req))
|
||||
} else if let Some(ref mut default) = self.default {
|
||||
Either::A(default.call(req))
|
||||
@ -515,6 +631,7 @@ impl ScopeEndpoint {
|
||||
}
|
||||
|
||||
impl NewService for ScopeEndpoint {
|
||||
type Config = ();
|
||||
type Request = ServiceRequest;
|
||||
type Response = ServiceResponse;
|
||||
type Error = Error;
|
||||
@ -536,7 +653,7 @@ mod tests {
|
||||
use crate::dev::{Body, ResponseBody};
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::test::{block_on, call_service, init_service, TestRequest};
|
||||
use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
|
||||
use crate::{guard, web, App, Error, HttpRequest, HttpResponse};
|
||||
|
||||
#[test]
|
||||
@ -946,4 +1063,76 @@ mod tests {
|
||||
HeaderValue::from_static("0001")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_override_data() {
|
||||
let mut srv = init_service(App::new().data(1usize).service(
|
||||
web::scope("app").data(10usize).route(
|
||||
"/t",
|
||||
web::get().to(|data: web::Data<usize>| {
|
||||
assert_eq!(*data, 10);
|
||||
let _ = data.clone();
|
||||
HttpResponse::Ok()
|
||||
}),
|
||||
),
|
||||
));
|
||||
|
||||
let req = TestRequest::with_uri("/app/t").to_request();
|
||||
let resp = call_service(&mut srv, req);
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_config() {
|
||||
let mut srv =
|
||||
init_service(App::new().service(web::scope("/app").configure(|s| {
|
||||
s.route("/path1", web::get().to(|| HttpResponse::Ok()));
|
||||
})));
|
||||
|
||||
let req = TestRequest::with_uri("/app/path1").to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_config_2() {
|
||||
let mut srv =
|
||||
init_service(App::new().service(web::scope("/app").configure(|s| {
|
||||
s.service(web::scope("/v1").configure(|s| {
|
||||
s.route("/", web::get().to(|| HttpResponse::Ok()));
|
||||
}));
|
||||
})));
|
||||
|
||||
let req = TestRequest::with_uri("/app/v1/").to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_url_for_external() {
|
||||
let mut srv =
|
||||
init_service(App::new().service(web::scope("/app").configure(|s| {
|
||||
s.service(web::scope("/v1").configure(|s| {
|
||||
s.external_resource(
|
||||
"youtube",
|
||||
"https://youtube.com/watch/{video_id}",
|
||||
);
|
||||
s.route(
|
||||
"/",
|
||||
web::get().to(|req: HttpRequest| {
|
||||
HttpResponse::Ok().body(format!(
|
||||
"{}",
|
||||
req.url_for("youtube", &["xxxxxx"]).unwrap().as_str()
|
||||
))
|
||||
}),
|
||||
);
|
||||
}));
|
||||
})));
|
||||
|
||||
let req = TestRequest::with_uri("/app/v1/").to_request();
|
||||
let resp = block_on(srv.call(req)).unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = read_body(resp);
|
||||
assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]);
|
||||
}
|
||||
}
|
||||
|
@ -51,8 +51,8 @@ struct Config {
|
||||
pub struct HttpServer<F, I, S, B>
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoNewService<S, ServerConfig>,
|
||||
S: NewService<ServerConfig, Request = Request>,
|
||||
I: IntoNewService<S>,
|
||||
S: NewService<Config = ServerConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -64,15 +64,15 @@ where
|
||||
config: Arc<Mutex<Config>>,
|
||||
backlog: i32,
|
||||
sockets: Vec<Socket>,
|
||||
builder: Option<ServerBuilder>,
|
||||
builder: ServerBuilder,
|
||||
_t: PhantomData<(S, B)>,
|
||||
}
|
||||
|
||||
impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoNewService<S, ServerConfig>,
|
||||
S: NewService<ServerConfig, Request = Request>,
|
||||
I: IntoNewService<S>,
|
||||
S: NewService<Config = ServerConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -91,7 +91,7 @@ where
|
||||
})),
|
||||
backlog: 1024,
|
||||
sockets: Vec::new(),
|
||||
builder: Some(ServerBuilder::default()),
|
||||
builder: ServerBuilder::default(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@ -101,7 +101,7 @@ where
|
||||
/// By default http server uses number of available logical cpu as threads
|
||||
/// count.
|
||||
pub fn workers(mut self, num: usize) -> Self {
|
||||
self.builder = Some(self.builder.take().unwrap().workers(num));
|
||||
self.builder = self.builder.workers(num);
|
||||
self
|
||||
}
|
||||
|
||||
@ -117,7 +117,7 @@ where
|
||||
/// This method should be called before `bind()` method call.
|
||||
pub fn backlog(mut self, backlog: i32) -> Self {
|
||||
self.backlog = backlog;
|
||||
self.builder = Some(self.builder.take().unwrap().backlog(backlog));
|
||||
self.builder = self.builder.backlog(backlog);
|
||||
self
|
||||
}
|
||||
|
||||
@ -128,7 +128,7 @@ where
|
||||
///
|
||||
/// By default max connections is set to a 25k.
|
||||
pub fn maxconn(mut self, num: usize) -> Self {
|
||||
self.builder = Some(self.builder.take().unwrap().maxconn(num));
|
||||
self.builder = self.builder.maxconn(num);
|
||||
self
|
||||
}
|
||||
|
||||
@ -139,7 +139,7 @@ where
|
||||
///
|
||||
/// By default max connections is set to a 256.
|
||||
pub fn maxconnrate(mut self, num: usize) -> Self {
|
||||
self.builder = Some(self.builder.take().unwrap().maxconnrate(num));
|
||||
self.builder = self.builder.maxconnrate(num);
|
||||
self
|
||||
}
|
||||
|
||||
@ -190,13 +190,13 @@ where
|
||||
|
||||
/// Stop actix system.
|
||||
pub fn system_exit(mut self) -> Self {
|
||||
self.builder = Some(self.builder.take().unwrap().system_exit());
|
||||
self.builder = self.builder.system_exit();
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable signal handling
|
||||
pub fn disable_signals(mut self) -> Self {
|
||||
self.builder = Some(self.builder.take().unwrap().disable_signals());
|
||||
self.builder = self.builder.disable_signals();
|
||||
self
|
||||
}
|
||||
|
||||
@ -207,8 +207,8 @@ where
|
||||
/// dropped.
|
||||
///
|
||||
/// By default shutdown timeout sets to 30 seconds.
|
||||
pub fn shutdown_timeout(mut self, sec: u16) -> Self {
|
||||
self.builder = Some(self.builder.take().unwrap().shutdown_timeout(sec));
|
||||
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
|
||||
self.builder = self.builder.shutdown_timeout(sec);
|
||||
self
|
||||
}
|
||||
|
||||
@ -240,7 +240,7 @@ where
|
||||
scheme: "http",
|
||||
});
|
||||
|
||||
self.builder = Some(self.builder.take().unwrap().listen(
|
||||
self.builder = self.builder.listen(
|
||||
format!("actix-web-service-{}", addr),
|
||||
lst,
|
||||
move || {
|
||||
@ -250,8 +250,7 @@ where
|
||||
.client_timeout(c.client_timeout)
|
||||
.finish(factory())
|
||||
},
|
||||
)?);
|
||||
|
||||
)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@ -260,20 +259,19 @@ where
|
||||
///
|
||||
/// This method sets alpn protocols to "h2" and "http/1.1"
|
||||
pub fn listen_ssl(
|
||||
mut self,
|
||||
self,
|
||||
lst: net::TcpListener,
|
||||
builder: SslAcceptorBuilder,
|
||||
) -> io::Result<Self> {
|
||||
self.listen_ssl_inner(lst, openssl_acceptor(builder)?)?;
|
||||
Ok(self)
|
||||
self.listen_ssl_inner(lst, openssl_acceptor(builder)?)
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
fn listen_ssl_inner(
|
||||
&mut self,
|
||||
mut self,
|
||||
lst: net::TcpListener,
|
||||
acceptor: SslAcceptor,
|
||||
) -> io::Result<()> {
|
||||
) -> io::Result<Self> {
|
||||
use actix_server::ssl::{OpensslAcceptor, SslError};
|
||||
|
||||
let acceptor = OpensslAcceptor::new(acceptor);
|
||||
@ -285,7 +283,7 @@ where
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
self.builder = Some(self.builder.take().unwrap().listen(
|
||||
self.builder = self.builder.listen(
|
||||
format!("actix-web-service-{}", addr),
|
||||
lst,
|
||||
move || {
|
||||
@ -300,8 +298,8 @@ where
|
||||
.map_init_err(|_| ()),
|
||||
)
|
||||
},
|
||||
)?);
|
||||
Ok(())
|
||||
)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-tls")]
|
||||
@ -309,20 +307,19 @@ where
|
||||
///
|
||||
/// This method sets alpn protocols to "h2" and "http/1.1"
|
||||
pub fn listen_rustls(
|
||||
mut self,
|
||||
self,
|
||||
lst: net::TcpListener,
|
||||
config: RustlsServerConfig,
|
||||
) -> io::Result<Self> {
|
||||
self.listen_rustls_inner(lst, config)?;
|
||||
Ok(self)
|
||||
self.listen_rustls_inner(lst, config)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-tls")]
|
||||
fn listen_rustls_inner(
|
||||
&mut self,
|
||||
mut self,
|
||||
lst: net::TcpListener,
|
||||
mut config: RustlsServerConfig,
|
||||
) -> io::Result<()> {
|
||||
) -> io::Result<Self> {
|
||||
use actix_server::ssl::{RustlsAcceptor, SslError};
|
||||
|
||||
let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()];
|
||||
@ -337,7 +334,7 @@ where
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
self.builder = Some(self.builder.take().unwrap().listen(
|
||||
self.builder = self.builder.listen(
|
||||
format!("actix-web-service-{}", addr),
|
||||
lst,
|
||||
move || {
|
||||
@ -352,8 +349,8 @@ where
|
||||
.map_init_err(|_| ()),
|
||||
)
|
||||
},
|
||||
)?);
|
||||
Ok(())
|
||||
)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// The socket address to bind
|
||||
@ -416,7 +413,7 @@ where
|
||||
let acceptor = openssl_acceptor(builder)?;
|
||||
|
||||
for lst in sockets {
|
||||
self.listen_ssl_inner(lst, acceptor.clone())?;
|
||||
self = self.listen_ssl_inner(lst, acceptor.clone())?;
|
||||
}
|
||||
|
||||
Ok(self)
|
||||
@ -433,7 +430,7 @@ where
|
||||
) -> io::Result<Self> {
|
||||
let sockets = self.bind2(addr)?;
|
||||
for lst in sockets {
|
||||
self.listen_rustls_inner(lst, config.clone())?;
|
||||
self = self.listen_rustls_inner(lst, config.clone())?;
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
@ -442,8 +439,8 @@ where
|
||||
impl<F, I, S, B> HttpServer<F, I, S, B>
|
||||
where
|
||||
F: Fn() -> I + Send + Clone + 'static,
|
||||
I: IntoNewService<S, ServerConfig>,
|
||||
S: NewService<ServerConfig, Request = Request>,
|
||||
I: IntoNewService<S>,
|
||||
S: NewService<Config = ServerConfig, Request = Request>,
|
||||
S::Error: Into<Error>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
@ -473,8 +470,8 @@ where
|
||||
/// sys.run() // <- Run actix system, this method starts all async processes
|
||||
/// }
|
||||
/// ```
|
||||
pub fn start(mut self) -> Server {
|
||||
self.builder.take().unwrap().start()
|
||||
pub fn start(self) -> Server {
|
||||
self.builder.start()
|
||||
}
|
||||
|
||||
/// Spawn new thread and start listening for incoming connections.
|
||||
|
@ -50,45 +50,46 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ServiceRequest {
|
||||
req: HttpRequest,
|
||||
payload: Payload,
|
||||
}
|
||||
/// An service http request
|
||||
///
|
||||
/// ServiceRequest allows mutable access to request's internal structures
|
||||
pub struct ServiceRequest(HttpRequest);
|
||||
|
||||
impl ServiceRequest {
|
||||
/// Construct service request from parts
|
||||
pub(crate) fn from_parts(req: HttpRequest, payload: Payload) -> Self {
|
||||
ServiceRequest { req, payload }
|
||||
/// Construct service request
|
||||
pub(crate) fn new(req: HttpRequest) -> Self {
|
||||
ServiceRequest(req)
|
||||
}
|
||||
|
||||
/// Deconstruct request into parts
|
||||
pub fn into_parts(self) -> (HttpRequest, Payload) {
|
||||
(self.req, self.payload)
|
||||
pub fn into_parts(mut self) -> (HttpRequest, Payload) {
|
||||
let pl = Rc::get_mut(&mut (self.0).0).unwrap().payload.take();
|
||||
(self.0, pl)
|
||||
}
|
||||
|
||||
/// Create service response
|
||||
#[inline]
|
||||
pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> {
|
||||
ServiceResponse::new(self.req, res.into())
|
||||
ServiceResponse::new(self.0, res.into())
|
||||
}
|
||||
|
||||
/// Create service response for error
|
||||
#[inline]
|
||||
pub fn error_response<B, E: Into<Error>>(self, err: E) -> ServiceResponse<B> {
|
||||
let res: Response = err.into().into();
|
||||
ServiceResponse::new(self.req, res.into_body())
|
||||
ServiceResponse::new(self.0, res.into_body())
|
||||
}
|
||||
|
||||
/// This method returns reference to the request head
|
||||
#[inline]
|
||||
pub fn head(&self) -> &RequestHead {
|
||||
&self.req.head()
|
||||
&self.0.head()
|
||||
}
|
||||
|
||||
/// This method returns reference to the request head
|
||||
#[inline]
|
||||
pub fn head_mut(&mut self) -> &mut RequestHead {
|
||||
self.req.head_mut()
|
||||
self.0.head_mut()
|
||||
}
|
||||
|
||||
/// Request's uri.
|
||||
@ -164,34 +165,39 @@ impl ServiceRequest {
|
||||
/// access the matched value for that segment.
|
||||
#[inline]
|
||||
pub fn match_info(&self) -> &Path<Url> {
|
||||
self.req.match_info()
|
||||
self.0.match_info()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn match_info_mut(&mut self) -> &mut Path<Url> {
|
||||
self.req.match_info_mut()
|
||||
self.0.match_info_mut()
|
||||
}
|
||||
|
||||
/// Service configuration
|
||||
#[inline]
|
||||
pub fn app_config(&self) -> &AppConfig {
|
||||
self.req.app_config()
|
||||
self.0.app_config()
|
||||
}
|
||||
|
||||
/// Get an application data stored with `App::data()` method during
|
||||
/// application configuration.
|
||||
pub fn app_data<T: 'static>(&self) -> Option<Data<T>> {
|
||||
if let Some(st) = self.req.0.app_data.get::<Data<T>>() {
|
||||
if let Some(st) = (self.0).0.app_data.get::<Data<T>>() {
|
||||
Some(st.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Set request payload.
|
||||
pub fn set_payload(&mut self, payload: Payload) {
|
||||
Rc::get_mut(&mut (self.0).0).unwrap().payload = payload;
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Set new app data container
|
||||
pub fn set_data_container(&mut self, extensions: Rc<Extensions>) {
|
||||
Rc::get_mut(&mut self.req.0).unwrap().app_data = extensions;
|
||||
Rc::get_mut(&mut (self.0).0).unwrap().app_data = extensions;
|
||||
}
|
||||
}
|
||||
|
||||
@ -213,18 +219,18 @@ impl HttpMessage for ServiceRequest {
|
||||
/// Request extensions
|
||||
#[inline]
|
||||
fn extensions(&self) -> Ref<Extensions> {
|
||||
self.req.extensions()
|
||||
self.0.extensions()
|
||||
}
|
||||
|
||||
/// Mutable reference to a the request's extensions
|
||||
#[inline]
|
||||
fn extensions_mut(&self) -> RefMut<Extensions> {
|
||||
self.req.extensions_mut()
|
||||
self.0.extensions_mut()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn take_payload(&mut self) -> Payload<Self::Stream> {
|
||||
std::mem::replace(&mut self.payload, Payload::None)
|
||||
Rc::get_mut(&mut (self.0).0).unwrap().payload.take()
|
||||
}
|
||||
}
|
||||
|
||||
@ -442,6 +448,7 @@ impl WebService {
|
||||
where
|
||||
F: IntoNewService<T>,
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
@ -467,6 +474,7 @@ struct WebServiceImpl<T> {
|
||||
impl<T> HttpServiceFactory for WebServiceImpl<T>
|
||||
where
|
||||
T: NewService<
|
||||
Config = (),
|
||||
Request = ServiceRequest,
|
||||
Response = ServiceResponse,
|
||||
Error = Error,
|
||||
|
107
src/test.rs
107
src/test.rs
@ -2,18 +2,19 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
|
||||
use actix_http::http::header::{ContentType, Header, HeaderName, IntoHeaderValue};
|
||||
use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
|
||||
use actix_http::test::TestRequest as HttpTestRequest;
|
||||
use actix_http::{cookie::Cookie, Extensions, Request};
|
||||
use actix_router::{Path, ResourceDef, Url};
|
||||
use actix_rt::Runtime;
|
||||
use actix_rt::{System, SystemRunner};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{FnService, IntoNewService, NewService, Service};
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use futures::future::{lazy, ok, Future, IntoFuture};
|
||||
use futures::Stream;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
|
||||
pub use actix_http::test::TestBuffer;
|
||||
@ -28,14 +29,14 @@ use crate::{Error, HttpRequest, HttpResponse};
|
||||
|
||||
thread_local! {
|
||||
static RT: RefCell<Inner> = {
|
||||
RefCell::new(Inner(Some(Runtime::new().unwrap())))
|
||||
RefCell::new(Inner(Some(System::builder().build())))
|
||||
};
|
||||
}
|
||||
|
||||
struct Inner(Option<Runtime>);
|
||||
struct Inner(Option<SystemRunner>);
|
||||
|
||||
impl Inner {
|
||||
fn get_mut(&mut self) -> &mut Runtime {
|
||||
fn get_mut(&mut self) -> &mut SystemRunner {
|
||||
self.0.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
@ -110,9 +111,10 @@ pub fn default_service(
|
||||
status_code: StatusCode,
|
||||
) -> impl Service<Request = ServiceRequest, Response = ServiceResponse<Body>, Error = Error>
|
||||
{
|
||||
FnService::new(move |req: ServiceRequest| {
|
||||
(move |req: ServiceRequest| {
|
||||
req.into_response(HttpResponse::build(status_code).finish())
|
||||
})
|
||||
.into_service()
|
||||
}
|
||||
|
||||
/// This method accepts application builder instance, and constructs
|
||||
@ -141,9 +143,9 @@ pub fn init_service<R, S, B, E>(
|
||||
app: R,
|
||||
) -> impl Service<Request = Request, Response = ServiceResponse<B>, Error = E>
|
||||
where
|
||||
R: IntoNewService<S, ServerConfig>,
|
||||
R: IntoNewService<S>,
|
||||
S: NewService<
|
||||
ServerConfig,
|
||||
Config = ServerConfig,
|
||||
Request = Request,
|
||||
Response = ServiceResponse<B>,
|
||||
Error = E,
|
||||
@ -247,7 +249,7 @@ where
|
||||
/// .header(header::CONTENT_TYPE, "application/json")
|
||||
/// .to_request();
|
||||
///
|
||||
/// let resp = call_service(&mut srv, req);
|
||||
/// let resp = test::call_service(&mut app, req);
|
||||
/// let result = test::read_body(resp);
|
||||
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
||||
/// }
|
||||
@ -476,6 +478,16 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Serialize `data` to JSON and set it as the request payload. The `Content-Type` header is
|
||||
/// set to `application/json`.
|
||||
pub fn set_json<T: Serialize>(mut self, data: &T) -> Self {
|
||||
let bytes =
|
||||
serde_json::to_string(data).expect("Failed to serialize test data to json");
|
||||
self.req.set_payload(bytes);
|
||||
self.req.set(ContentType::json());
|
||||
self
|
||||
}
|
||||
|
||||
/// Set application data. This is equivalent of `App::data()` method
|
||||
/// for testing purpose.
|
||||
pub fn data<T: 'static>(mut self, data: T) -> Self {
|
||||
@ -500,16 +512,15 @@ impl TestRequest {
|
||||
let (head, payload) = self.req.finish().into_parts();
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
let req = HttpRequest::new(
|
||||
ServiceRequest::new(HttpRequest::new(
|
||||
self.path,
|
||||
head,
|
||||
payload,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
Rc::new(self.app_data),
|
||||
HttpRequestPool::create(),
|
||||
);
|
||||
|
||||
ServiceRequest::from_parts(req, payload)
|
||||
))
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `ServiceResponse` instance
|
||||
@ -519,12 +530,13 @@ impl TestRequest {
|
||||
|
||||
/// Complete request creation and generate `HttpRequest` instance
|
||||
pub fn to_http_request(mut self) -> HttpRequest {
|
||||
let (head, _) = self.req.finish().into_parts();
|
||||
let (head, payload) = self.req.finish().into_parts();
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
HttpRequest::new(
|
||||
self.path,
|
||||
head,
|
||||
payload,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
Rc::new(self.app_data),
|
||||
@ -540,6 +552,7 @@ impl TestRequest {
|
||||
let req = HttpRequest::new(
|
||||
self.path,
|
||||
head,
|
||||
Payload::None,
|
||||
Rc::new(self.rmap),
|
||||
AppConfig::new(self.config),
|
||||
Rc::new(self.app_data),
|
||||
@ -552,6 +565,7 @@ impl TestRequest {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_http::httpmessage::HttpMessage;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::SystemTime;
|
||||
|
||||
@ -656,6 +670,31 @@ mod tests {
|
||||
assert_eq!(&result.id, "12345");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_response_json() {
|
||||
let mut app = init_service(App::new().service(web::resource("/people").route(
|
||||
web::post().to(|person: web::Json<Person>| {
|
||||
HttpResponse::Ok().json(person.into_inner())
|
||||
}),
|
||||
)));
|
||||
|
||||
let payload = Person {
|
||||
id: "12345".to_string(),
|
||||
name: "User name".to_string(),
|
||||
};
|
||||
|
||||
let req = TestRequest::post()
|
||||
.uri("/people")
|
||||
.set_json(&payload)
|
||||
.to_request();
|
||||
|
||||
assert_eq!(req.content_type(), "application/json");
|
||||
|
||||
let result: Person = read_response_json(&mut app, req);
|
||||
assert_eq!(&result.id, "12345");
|
||||
assert_eq!(&result.name, "User name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_async_with_block() {
|
||||
fn async_with_block() -> impl Future<Item = HttpResponse, Error = Error> {
|
||||
@ -675,4 +714,42 @@ mod tests {
|
||||
let res = block_fn(|| app.call(req)).unwrap();
|
||||
assert!(res.status().is_success());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_actor() {
|
||||
use actix::Actor;
|
||||
|
||||
struct MyActor;
|
||||
|
||||
struct Num(usize);
|
||||
impl actix::Message for Num {
|
||||
type Result = usize;
|
||||
}
|
||||
impl actix::Actor for MyActor {
|
||||
type Context = actix::Context<Self>;
|
||||
}
|
||||
impl actix::Handler<Num> for MyActor {
|
||||
type Result = usize;
|
||||
fn handle(&mut self, msg: Num, _: &mut Self::Context) -> Self::Result {
|
||||
msg.0
|
||||
}
|
||||
}
|
||||
|
||||
let addr = run_on(|| MyActor.start());
|
||||
let mut app = init_service(App::new().service(
|
||||
web::resource("/index.html").to_async(move || {
|
||||
addr.send(Num(1)).from_err().and_then(|res| {
|
||||
if res == 1 {
|
||||
HttpResponse::Ok()
|
||||
} else {
|
||||
HttpResponse::BadRequest()
|
||||
}
|
||||
})
|
||||
}),
|
||||
));
|
||||
|
||||
let req = TestRequest::post().uri("/index.html").to_request();
|
||||
let res = block_fn(|| app.call(req)).unwrap();
|
||||
assert!(res.status().is_success());
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
//! Json extractor/responder
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::{fmt, ops};
|
||||
|
||||
use bytes::BytesMut;
|
||||
@ -168,22 +168,22 @@ impl<T> FromRequest for Json<T>
|
||||
where
|
||||
T: DeserializeOwned + 'static,
|
||||
{
|
||||
type Config = JsonConfig;
|
||||
type Error = Error;
|
||||
type Future = Box<Future<Item = Self, Error = Error>>;
|
||||
type Config = JsonConfig;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||
let req2 = req.clone();
|
||||
let (limit, err) = req
|
||||
.app_data::<JsonConfig>()
|
||||
.map(|c| (c.limit, c.ehandler.clone()))
|
||||
.unwrap_or((32768, None));
|
||||
let (limit, err, ctype) = req
|
||||
.app_data::<Self::Config>()
|
||||
.map(|c| (c.limit, c.ehandler.clone(), c.content_type.clone()))
|
||||
.unwrap_or((32768, None, None));
|
||||
|
||||
let path = req.path().to_string();
|
||||
|
||||
Box::new(
|
||||
JsonBody::new(req, payload)
|
||||
JsonBody::new(req, payload, ctype)
|
||||
.limit(limit)
|
||||
.map_err(move |e| {
|
||||
log::debug!(
|
||||
@ -224,6 +224,9 @@ where
|
||||
/// // change json extractor configuration
|
||||
/// web::Json::<Info>::configure(|cfg| {
|
||||
/// cfg.limit(4096)
|
||||
/// .content_type(|mime| { // <- accept text/plain content type
|
||||
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||
/// })
|
||||
/// .error_handler(|err, req| { // <- create custom error response
|
||||
/// error::InternalError::from_response(
|
||||
/// err, HttpResponse::Conflict().finish()).into()
|
||||
@ -236,7 +239,8 @@ where
|
||||
#[derive(Clone)]
|
||||
pub struct JsonConfig {
|
||||
limit: usize,
|
||||
ehandler: Option<Rc<Fn(JsonPayloadError, &HttpRequest) -> Error>>,
|
||||
ehandler: Option<Arc<dyn Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync>>,
|
||||
content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl JsonConfig {
|
||||
@ -249,9 +253,18 @@ impl JsonConfig {
|
||||
/// Set custom error handler
|
||||
pub fn error_handler<F>(mut self, f: F) -> Self
|
||||
where
|
||||
F: Fn(JsonPayloadError, &HttpRequest) -> Error + 'static,
|
||||
F: Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync + 'static,
|
||||
{
|
||||
self.ehandler = Some(Rc::new(f));
|
||||
self.ehandler = Some(Arc::new(f));
|
||||
self
|
||||
}
|
||||
|
||||
/// Set predicate for allowed content types
|
||||
pub fn content_type<F>(mut self, predicate: F) -> Self
|
||||
where
|
||||
F: Fn(mime::Mime) -> bool + Send + Sync + 'static,
|
||||
{
|
||||
self.content_type = Some(Arc::new(predicate));
|
||||
self
|
||||
}
|
||||
}
|
||||
@ -261,6 +274,7 @@ impl Default for JsonConfig {
|
||||
JsonConfig {
|
||||
limit: 32768,
|
||||
ehandler: None,
|
||||
content_type: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -271,6 +285,7 @@ impl Default for JsonConfig {
|
||||
/// Returns error:
|
||||
///
|
||||
/// * content type is not `application/json`
|
||||
/// (unless specified in [`JsonConfig`](struct.JsonConfig.html))
|
||||
/// * content length is greater than 256k
|
||||
pub struct JsonBody<U> {
|
||||
limit: usize,
|
||||
@ -285,13 +300,20 @@ where
|
||||
U: DeserializeOwned + 'static,
|
||||
{
|
||||
/// Create `JsonBody` for request.
|
||||
pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
|
||||
pub fn new(
|
||||
req: &HttpRequest,
|
||||
payload: &mut Payload,
|
||||
ctype: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
|
||||
) -> Self {
|
||||
// check content-type
|
||||
let json = if let Ok(Some(mime)) = req.mime_type() {
|
||||
mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON)
|
||||
mime.subtype() == mime::JSON
|
||||
|| mime.suffix() == Some(mime::JSON)
|
||||
|| ctype.as_ref().map_or(false, |predicate| predicate(mime))
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if !json {
|
||||
return JsonBody {
|
||||
limit: 262_144,
|
||||
@ -512,7 +534,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_json_body() {
|
||||
let (req, mut pl) = TestRequest::default().to_http_parts();
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl));
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None));
|
||||
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
||||
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
@ -521,7 +543,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("application/text"),
|
||||
)
|
||||
.to_http_parts();
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl));
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None));
|
||||
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
|
||||
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
@ -535,7 +557,7 @@ mod tests {
|
||||
)
|
||||
.to_http_parts();
|
||||
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl).limit(100));
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None).limit(100));
|
||||
assert!(json_eq(json.err().unwrap(), JsonPayloadError::Overflow));
|
||||
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
@ -550,7 +572,7 @@ mod tests {
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.to_http_parts();
|
||||
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl));
|
||||
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None));
|
||||
assert_eq!(
|
||||
json.ok().unwrap(),
|
||||
MyObject {
|
||||
@ -558,4 +580,62 @@ mod tests {
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_json_and_bad_content_type() {
|
||||
let (req, mut pl) = TestRequest::with_header(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static("text/plain"),
|
||||
)
|
||||
.header(
|
||||
header::CONTENT_LENGTH,
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().limit(4096))
|
||||
.to_http_parts();
|
||||
|
||||
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
|
||||
assert!(s.is_err())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_json_and_good_custom_content_type() {
|
||||
let (req, mut pl) = TestRequest::with_header(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static("text/plain"),
|
||||
)
|
||||
.header(
|
||||
header::CONTENT_LENGTH,
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||
}))
|
||||
.to_http_parts();
|
||||
|
||||
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
|
||||
assert!(s.is_ok())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_json_and_bad_custom_content_type() {
|
||||
let (req, mut pl) = TestRequest::with_header(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static("text/html"),
|
||||
)
|
||||
.header(
|
||||
header::CONTENT_LENGTH,
|
||||
header::HeaderValue::from_static("16"),
|
||||
)
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
|
||||
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||
}))
|
||||
.to_http_parts();
|
||||
|
||||
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
|
||||
assert!(s.is_err())
|
||||
}
|
||||
}
|
||||
|
@ -9,6 +9,6 @@ pub(crate) mod readlines;
|
||||
|
||||
pub use self::form::{Form, FormConfig};
|
||||
pub use self::json::{Json, JsonConfig};
|
||||
pub use self::path::Path;
|
||||
pub use self::path::{Path, PathConfig};
|
||||
pub use self::payload::{Payload, PayloadConfig};
|
||||
pub use self::query::Query;
|
||||
pub use self::query::{Query, QueryConfig};
|
||||
|
@ -1,5 +1,6 @@
|
||||
//! Path extractor
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::{fmt, ops};
|
||||
|
||||
use actix_http::error::{Error, ErrorNotFound};
|
||||
@ -7,6 +8,7 @@ use actix_router::PathDeserializer;
|
||||
use serde::de;
|
||||
|
||||
use crate::dev::Payload;
|
||||
use crate::error::PathError;
|
||||
use crate::request::HttpRequest;
|
||||
use crate::FromRequest;
|
||||
|
||||
@ -156,15 +158,89 @@ impl<T> FromRequest for Path<T>
|
||||
where
|
||||
T: de::DeserializeOwned,
|
||||
{
|
||||
type Config = ();
|
||||
type Error = Error;
|
||||
type Future = Result<Self, Error>;
|
||||
type Config = PathConfig;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let error_handler = req
|
||||
.app_data::<Self::Config>()
|
||||
.map(|c| c.ehandler.clone())
|
||||
.unwrap_or(None);
|
||||
|
||||
de::Deserialize::deserialize(PathDeserializer::new(req.match_info()))
|
||||
.map(|inner| Path { inner })
|
||||
.map_err(ErrorNotFound)
|
||||
.map_err(move |e| {
|
||||
log::debug!(
|
||||
"Failed during Path extractor deserialization. \
|
||||
Request path: {:?}",
|
||||
req.path()
|
||||
);
|
||||
if let Some(error_handler) = error_handler {
|
||||
let e = PathError::Deserialize(e);
|
||||
(error_handler)(e, req)
|
||||
} else {
|
||||
ErrorNotFound(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Path extractor configuration
|
||||
///
|
||||
/// ```rust
|
||||
/// # #[macro_use]
|
||||
/// # extern crate serde_derive;
|
||||
/// use actix_web::web::PathConfig;
|
||||
/// use actix_web::{error, web, App, FromRequest, HttpResponse};
|
||||
///
|
||||
/// #[derive(Deserialize, Debug)]
|
||||
/// enum Folder {
|
||||
/// #[serde(rename = "inbox")]
|
||||
/// Inbox,
|
||||
/// #[serde(rename = "outbox")]
|
||||
/// Outbox,
|
||||
/// }
|
||||
///
|
||||
/// // deserialize `Info` from request's path
|
||||
/// fn index(folder: web::Path<Folder>) -> String {
|
||||
/// format!("Selected folder: {:?}!", folder)
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/messages/{folder}")
|
||||
/// .data(PathConfig::default().error_handler(|err, req| {
|
||||
/// error::InternalError::from_response(
|
||||
/// err,
|
||||
/// HttpResponse::Conflict().finish(),
|
||||
/// )
|
||||
/// .into()
|
||||
/// }))
|
||||
/// .route(web::post().to(index)),
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Clone)]
|
||||
pub struct PathConfig {
|
||||
ehandler: Option<Arc<Fn(PathError, &HttpRequest) -> Error + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl PathConfig {
|
||||
/// Set custom error handler
|
||||
pub fn error_handler<F>(mut self, f: F) -> Self
|
||||
where
|
||||
F: Fn(PathError, &HttpRequest) -> Error + Send + Sync + 'static,
|
||||
{
|
||||
self.ehandler = Some(Arc::new(f));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PathConfig {
|
||||
fn default() -> Self {
|
||||
PathConfig { ehandler: None }
|
||||
}
|
||||
}
|
||||
|
||||
@ -176,6 +252,7 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
use crate::test::{block_on, TestRequest};
|
||||
use crate::{error, http, HttpResponse};
|
||||
|
||||
#[derive(Deserialize, Debug, Display)]
|
||||
#[display(fmt = "MyStruct({}, {})", key, value)]
|
||||
@ -271,4 +348,21 @@ mod tests {
|
||||
assert_eq!(res[1], "32".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_custom_err_handler() {
|
||||
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
|
||||
.data(PathConfig::default().error_handler(|err, _| {
|
||||
error::InternalError::from_response(
|
||||
err,
|
||||
HttpResponse::Conflict().finish(),
|
||||
)
|
||||
.into()
|
||||
}))
|
||||
.to_http_parts();
|
||||
|
||||
let s = block_on(Path::<(usize,)>::from_request(&req, &mut pl)).unwrap_err();
|
||||
let res: HttpResponse = s.into();
|
||||
|
||||
assert_eq!(res.status(), http::StatusCode::CONFLICT);
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
//! Query extractor
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::{fmt, ops};
|
||||
|
||||
use actix_http::error::Error;
|
||||
@ -7,6 +8,7 @@ use serde::de;
|
||||
use serde_urlencoded;
|
||||
|
||||
use crate::dev::Payload;
|
||||
use crate::error::QueryPayloadError;
|
||||
use crate::extract::FromRequest;
|
||||
use crate::request::HttpRequest;
|
||||
|
||||
@ -50,6 +52,16 @@ impl<T> Query<T> {
|
||||
pub fn into_inner(self) -> T {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Get query parameters from the path
|
||||
pub fn from_query(query_str: &str) -> Result<Self, QueryPayloadError>
|
||||
where
|
||||
T: de::DeserializeOwned,
|
||||
{
|
||||
serde_urlencoded::from_str::<T>(query_str)
|
||||
.map(|val| Ok(Query(val)))
|
||||
.unwrap_or_else(move |e| Err(QueryPayloadError::Deserialize(e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ops::Deref for Query<T> {
|
||||
@ -115,38 +127,123 @@ impl<T> FromRequest for Query<T>
|
||||
where
|
||||
T: de::DeserializeOwned,
|
||||
{
|
||||
type Config = ();
|
||||
type Error = Error;
|
||||
type Future = Result<Self, Error>;
|
||||
type Config = QueryConfig;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let error_handler = req
|
||||
.app_data::<Self::Config>()
|
||||
.map(|c| c.ehandler.clone())
|
||||
.unwrap_or(None);
|
||||
|
||||
serde_urlencoded::from_str::<T>(req.query_string())
|
||||
.map(|val| Ok(Query(val)))
|
||||
.unwrap_or_else(|e| {
|
||||
.unwrap_or_else(move |e| {
|
||||
let e = QueryPayloadError::Deserialize(e);
|
||||
|
||||
log::debug!(
|
||||
"Failed during Query extractor deserialization. \
|
||||
Request path: {:?}",
|
||||
req.path()
|
||||
);
|
||||
Err(e.into())
|
||||
|
||||
let e = if let Some(error_handler) = error_handler {
|
||||
(error_handler)(e, req)
|
||||
} else {
|
||||
e.into()
|
||||
};
|
||||
|
||||
Err(e)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Query extractor configuration
|
||||
///
|
||||
/// ```rust
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// use actix_web::{error, web, App, FromRequest, HttpResponse};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct Info {
|
||||
/// username: String,
|
||||
/// }
|
||||
///
|
||||
/// /// deserialize `Info` from request's querystring
|
||||
/// fn index(info: web::Query<Info>) -> String {
|
||||
/// format!("Welcome {}!", info.username)
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().service(
|
||||
/// web::resource("/index.html").data(
|
||||
/// // change query extractor configuration
|
||||
/// web::Query::<Info>::configure(|cfg| {
|
||||
/// cfg.error_handler(|err, req| { // <- create custom error response
|
||||
/// error::InternalError::from_response(
|
||||
/// err, HttpResponse::Conflict().finish()).into()
|
||||
/// })
|
||||
/// }))
|
||||
/// .route(web::post().to(index))
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Clone)]
|
||||
pub struct QueryConfig {
|
||||
ehandler: Option<Arc<Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl QueryConfig {
|
||||
/// Set custom error handler
|
||||
pub fn error_handler<F>(mut self, f: F) -> Self
|
||||
where
|
||||
F: Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync + 'static,
|
||||
{
|
||||
self.ehandler = Some(Arc::new(f));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for QueryConfig {
|
||||
fn default() -> Self {
|
||||
QueryConfig { ehandler: None }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_http::http::StatusCode;
|
||||
use derive_more::Display;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use super::*;
|
||||
use crate::error::InternalError;
|
||||
use crate::test::TestRequest;
|
||||
use crate::HttpResponse;
|
||||
|
||||
#[derive(Deserialize, Debug, Display)]
|
||||
struct Id {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_service_request_extract() {
|
||||
let req = TestRequest::with_uri("/name/user1/").to_srv_request();
|
||||
assert!(Query::<Id>::from_query(&req.query_string()).is_err());
|
||||
|
||||
let req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request();
|
||||
let mut s = Query::<Id>::from_query(&req.query_string()).unwrap();
|
||||
|
||||
assert_eq!(s.id, "test");
|
||||
assert_eq!(format!("{}, {:?}", s, s), "test, Id { id: \"test\" }");
|
||||
|
||||
s.id = "test1".to_string();
|
||||
let s = s.into_inner();
|
||||
assert_eq!(s.id, "test1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_extract() {
|
||||
let req = TestRequest::with_uri("/name/user1/").to_srv_request();
|
||||
@ -164,4 +261,27 @@ mod tests {
|
||||
let s = s.into_inner();
|
||||
assert_eq!(s.id, "test1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_custom_error_responder() {
|
||||
let req = TestRequest::with_uri("/name/user1/")
|
||||
.data(QueryConfig::default().error_handler(|e, _| {
|
||||
let resp = HttpResponse::UnprocessableEntity().finish();
|
||||
InternalError::from_response(e, resp).into()
|
||||
}))
|
||||
.to_srv_request();
|
||||
|
||||
let (req, mut pl) = req.into_parts();
|
||||
let query = Query::<Id>::from_request(&req, &mut pl);
|
||||
|
||||
assert!(query.is_err());
|
||||
assert_eq!(
|
||||
query
|
||||
.unwrap_err()
|
||||
.as_response_error()
|
||||
.error_response()
|
||||
.status(),
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,13 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-06-05
|
||||
|
||||
* Add license files
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
* Update awc and actix-http deps
|
||||
|
||||
## [0.1.1] - 2019-04-24
|
||||
|
||||
* Always make new connection for http client
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http-test"
|
||||
version = "0.1.1"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http test server"
|
||||
readme = "README.md"
|
||||
@ -32,10 +32,10 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-service = "0.3.6"
|
||||
actix-server = "0.4.3"
|
||||
actix-utils = "0.3.5"
|
||||
awc = "0.1.1"
|
||||
actix-service = "0.4.0"
|
||||
actix-server = "0.5.1"
|
||||
actix-utils = "0.4.1"
|
||||
awc = "0.2.1"
|
||||
|
||||
base64 = "0.10"
|
||||
bytes = "0.4"
|
||||
@ -55,5 +55,5 @@ tokio-timer = "0.2"
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = "1.0.0-beta.1"
|
||||
actix-http = "0.1.2"
|
||||
actix-web = "1.0.0-rc"
|
||||
actix-http = "0.2.3"
|
||||
|
1
test-server/LICENSE-APACHE
Symbolic link
1
test-server/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
test-server/LICENSE-MIT
Symbolic link
1
test-server/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -9,16 +9,30 @@ use actix_server::{Server, StreamServiceFactory};
|
||||
use awc::{error::PayloadError, ws, Client, ClientRequest, ClientResponse, Connector};
|
||||
use bytes::Bytes;
|
||||
use futures::future::lazy;
|
||||
use futures::{Future, Stream};
|
||||
use futures::{Future, IntoFuture, Stream};
|
||||
use http::Method;
|
||||
use net2::TcpBuilder;
|
||||
|
||||
thread_local! {
|
||||
static RT: RefCell<Runtime> = {
|
||||
RefCell::new(Runtime::new().unwrap())
|
||||
static RT: RefCell<Inner> = {
|
||||
RefCell::new(Inner(Some(Runtime::new().unwrap())))
|
||||
};
|
||||
}
|
||||
|
||||
struct Inner(Option<Runtime>);
|
||||
|
||||
impl Inner {
|
||||
fn get_mut(&mut self) -> &mut Runtime {
|
||||
self.0.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inner {
|
||||
fn drop(&mut self) {
|
||||
std::mem::forget(self.0.take().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the provided future, blocking the current thread until the future
|
||||
/// completes.
|
||||
///
|
||||
@ -31,21 +45,27 @@ thread_local! {
|
||||
/// This function panics on nested call.
|
||||
pub fn block_on<F>(f: F) -> Result<F::Item, F::Error>
|
||||
where
|
||||
F: Future,
|
||||
F: IntoFuture,
|
||||
{
|
||||
RT.with(move |rt| rt.borrow_mut().block_on(f))
|
||||
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(f.into_future()))
|
||||
}
|
||||
|
||||
/// Runs the provided function, with runtime enabled.
|
||||
/// Runs the provided function, blocking the current thread until the resul
|
||||
/// future completes.
|
||||
///
|
||||
/// This function can be used to synchronously block the current thread
|
||||
/// until the provided `future` has resolved either successfully or with an
|
||||
/// error. The result of the future is then returned from this function
|
||||
/// call.
|
||||
///
|
||||
/// Note that this function is intended to be used only for testing purpose.
|
||||
/// This function panics on nested call.
|
||||
pub fn run_on<F, R>(f: F) -> R
|
||||
pub fn block_fn<F, R>(f: F) -> Result<R::Item, R::Error>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
F: FnOnce() -> R,
|
||||
R: IntoFuture,
|
||||
{
|
||||
RT.with(move |rt| rt.borrow_mut().block_on(lazy(|| Ok::<_, ()>(f()))))
|
||||
.unwrap()
|
||||
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f())))
|
||||
}
|
||||
|
||||
/// The `TestServer` type.
|
||||
@ -235,6 +255,16 @@ impl TestServerRuntime {
|
||||
self.client.head(self.surl(path.as_ref()).as_str())
|
||||
}
|
||||
|
||||
/// Create `PUT` request
|
||||
pub fn put<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
||||
self.client.put(self.url(path.as_ref()).as_str())
|
||||
}
|
||||
|
||||
/// Create https `PUT` request
|
||||
pub fn sput<S: AsRef<str>>(&self, path: S) -> ClientRequest {
|
||||
self.client.put(self.surl(path.as_ref()).as_str())
|
||||
}
|
||||
|
||||
/// Connect to test http server
|
||||
pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest {
|
||||
self.client.request(method, path.as_ref())
|
||||
|
Reference in New Issue
Block a user