mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-04 18:06:23 +02:00
Compare commits
66 Commits
Author | SHA1 | Date | |
---|---|---|---|
3378247bee | |||
7507412a1d | |||
6b9a193aa8 | |||
c2979760b5 | |||
1fcf1d4a49 | |||
4012606910 | |||
e975124630 | |||
6862aa6ee7 | |||
8a22558f25 | |||
b5b9f9656e | |||
2fffc55d34 | |||
7d39f1582e | |||
75ed053a35 | |||
cfedf5fff4 | |||
be73a36339 | |||
1ad8ba2604 | |||
6848a12095 | |||
4797298706 | |||
5eaf4cbefd | |||
7f1844e541 | |||
6c7ac7fc22 | |||
42f9e1034b | |||
e3cd0fdd13 | |||
40ff550460 | |||
7119340d44 | |||
e140bc3906 | |||
fdc08d365d | |||
8f1b88e39e | |||
6a40a0a466 | |||
89fc6b6ac9 | |||
afa67b838a | |||
f7b7d282bf | |||
09780ea9f3 | |||
a7dab950f3 | |||
ec0737e392 | |||
d664993d56 | |||
a9c6c57a67 | |||
08e7374eee | |||
42da1448fb | |||
9f9e0b98ad | |||
556646aaec | |||
174fb0b5f4 | |||
836706653b | |||
17f1a2b92a | |||
3b08b16c11 | |||
68eb2f26c9 | |||
72757887c9 | |||
eb5dbd43ae | |||
1f1dfac3f9 | |||
2479b14aba | |||
ac24703512 | |||
db0091ba6f | |||
2159158c30 | |||
76d790425f | |||
90968d4333 | |||
577a509875 | |||
a9728abfc8 | |||
14d1b8e2b6 | |||
285c73e95e | |||
483db7028c | |||
082ff46041 | |||
f32e8f22c8 | |||
766dde7c42 | |||
b68687044e | |||
c9e84e9dd3 | |||
0126ac46fc |
@ -31,12 +31,12 @@ before_script:
|
||||
|
||||
script:
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" != "beta" ]]; then
|
||||
if [[ "$TRAVIS_RUST_VERSION" != "1.24.0" ]]; then
|
||||
cargo clean
|
||||
cargo test --features="alpn,tls" -- --nocapture
|
||||
fi
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "beta" ]]; then
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "1.24.0" ]]; then
|
||||
bash <(curl https://raw.githubusercontent.com/xd009642/tarpaulin/master/travis-install.sh)
|
||||
USE_SKEPTIC=1 cargo tarpaulin --out Xml --no-count
|
||||
bash <(curl -s https://codecov.io/bash)
|
||||
|
91
CHANGES.md
91
CHANGES.md
@ -1,5 +1,96 @@
|
||||
# Changes
|
||||
|
||||
## [0.6.15] - 2018-07-11
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix h2 compatibility #352
|
||||
|
||||
* Fix duplicate tail of StaticFiles with index_file. #344
|
||||
|
||||
|
||||
## [0.6.14] - 2018-06-21
|
||||
|
||||
### Added
|
||||
|
||||
* Allow to disable masking for websockets client
|
||||
|
||||
### Fixed
|
||||
|
||||
* SendRequest execution fails with the "internal error: entered unreachable code" #329
|
||||
|
||||
|
||||
## [0.6.13] - 2018-06-13
|
||||
|
||||
### Fixed
|
||||
|
||||
* http/2 end-of-frame is not set if body is empty bytes #307
|
||||
|
||||
* InternalError can trigger memory unsafety #301
|
||||
|
||||
* Fix docs.rs build
|
||||
|
||||
|
||||
## [0.6.12] - 2018-06-08
|
||||
|
||||
### Added
|
||||
|
||||
* Add `Host` filter #287
|
||||
|
||||
* Allow to filter applications
|
||||
|
||||
* Improved failure interoperability with downcasting #285
|
||||
|
||||
* Allow to use custom resolver for `ClientConnector`
|
||||
|
||||
|
||||
### Deprecated
|
||||
|
||||
* `Error::cause()` and introduces failure interoperability functions and downcasting.
|
||||
|
||||
|
||||
## [0.6.11] - 2018-06-05
|
||||
|
||||
### Fixed
|
||||
|
||||
* Support chunked encoding for UrlEncoded body #262
|
||||
|
||||
* `HttpRequest::url_for()` for a named route with no variables segments #265
|
||||
|
||||
* `Middleware::response()` is not invoked if error result was returned by another `Middleware::start()` #255
|
||||
|
||||
* CORS: Do not validate Origin header on non-OPTION requests #271
|
||||
|
||||
* Fix multipart upload "Incomplete" error #282
|
||||
|
||||
|
||||
## [0.6.10] - 2018-05-24
|
||||
|
||||
### Added
|
||||
|
||||
* Allow to use path without traling slashes for scope registration #241
|
||||
|
||||
* Allow to set encoding for exact NamedFile #239
|
||||
|
||||
### Fixed
|
||||
|
||||
* `TestServer::post()` actually sends `GET` request #240
|
||||
|
||||
|
||||
## 0.6.9 (2018-05-22)
|
||||
|
||||
* Drop connection if request's payload is not fully consumed #236
|
||||
|
||||
* Fix streaming response with body compression
|
||||
|
||||
|
||||
## 0.6.8 (2018-05-20)
|
||||
|
||||
* Fix scope resource path extractor #234
|
||||
|
||||
* Re-use tcp listener on pause/resume
|
||||
|
||||
|
||||
## 0.6.7 (2018-05-17)
|
||||
|
||||
* Fix compilation with --no-default-features
|
||||
|
@ -1,11 +1,11 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "0.6.7"
|
||||
version = "0.6.15"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
keywords = ["http", "web", "framework", "async", "futures"]
|
||||
homepage = "https://github.com/actix/actix-web"
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
documentation = "https://docs.rs/actix-web/"
|
||||
categories = ["network-programming", "asynchronous",
|
||||
@ -46,8 +46,11 @@ flate2-c = ["flate2/miniz-sys"]
|
||||
# rust backend for flate2 crate
|
||||
flate2-rust = ["flate2/rust_backend"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["tls", "alpn", "session", "brotli", "flate2-c"]
|
||||
|
||||
[dependencies]
|
||||
actix = "^0.5.5"
|
||||
actix = "^0.5.8"
|
||||
|
||||
base64 = "0.9"
|
||||
bitflags = "1.0"
|
||||
|
14
README.md
14
README.md
@ -2,12 +2,12 @@
|
||||
|
||||
Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
|
||||
* Supported *HTTP/1.x* and [*HTTP/2.0*](https://actix.rs/book/actix-web/sec-12-http2.html) protocols
|
||||
* Supported *HTTP/1.x* and [*HTTP/2.0*](https://actix.rs/docs/http2/) protocols
|
||||
* Streaming and pipelining
|
||||
* Keep-alive and slow requests handling
|
||||
* Client/server [WebSockets](https://actix.rs/book/actix-web/sec-11-websockets.html) support
|
||||
* Client/server [WebSockets](https://actix.rs/docs/websockets/) support
|
||||
* Transparent content compression/decompression (br, gzip, deflate)
|
||||
* Configurable [request routing](https://actix.rs/book/actix-web/sec-6-url-dispatch.html)
|
||||
* Configurable [request routing](https://actix.rs/docs/url-dispatch/)
|
||||
* Graceful server shutdown
|
||||
* Multipart streams
|
||||
* Static assets
|
||||
@ -18,12 +18,12 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
[DefaultHeaders](https://actix.rs/book/actix-web/sec-9-middlewares.html#default-headers),
|
||||
[CORS](https://actix.rs/actix-web/actix_web/middleware/cors/index.html),
|
||||
[CSRF](https://actix.rs/actix-web/actix_web/middleware/csrf/index.html))
|
||||
* Includes an asynchronous [HTTP client](https://github.com/actix/actix-web/blob/master/src/client/mod.rs)
|
||||
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
|
||||
* Built on top of [Actix actor framework](https://github.com/actix/actix)
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [User Guide](https://actix.rs/book/actix-web/)
|
||||
* [User Guide](https://actix.rs/docs/)
|
||||
* [API Documentation (Development)](https://actix.rs/actix-web/actix_web/)
|
||||
* [API Documentation (Releases)](https://docs.rs/actix-web/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
@ -34,9 +34,9 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
|
||||
```rust
|
||||
extern crate actix_web;
|
||||
use actix_web::{http, server, App, Path};
|
||||
use actix_web::{http, server, App, Path, Responder};
|
||||
|
||||
fn index(info: Path<(u32, String)>) -> String {
|
||||
fn index(info: Path<(u32, String)>) -> impl Responder {
|
||||
format!("Hello {}! id:{}", info.1, info.0)
|
||||
}
|
||||
|
||||
|
@ -22,6 +22,7 @@ pub struct HttpApplication<S = ()> {
|
||||
prefix_len: usize,
|
||||
router: Router,
|
||||
inner: Rc<UnsafeCell<Inner<S>>>,
|
||||
filters: Option<Vec<Box<Predicate<S>>>>,
|
||||
middlewares: Rc<Vec<Box<Middleware<S>>>>,
|
||||
}
|
||||
|
||||
@ -107,16 +108,12 @@ impl<S: 'static> HttpApplication<S> {
|
||||
}
|
||||
}
|
||||
|
||||
let prefix_len = inner.prefix + prefix_len - 1;
|
||||
let prefix_len = inner.prefix + prefix_len;
|
||||
let path: &'static str =
|
||||
unsafe { &*(&req.path()[prefix_len..] as *const _) };
|
||||
|
||||
req.set_prefix_len(prefix_len as u16);
|
||||
if path.is_empty() {
|
||||
req.match_info_mut().set("tail", "/");
|
||||
} else {
|
||||
req.match_info_mut().set("tail", path);
|
||||
}
|
||||
req.match_info_mut().set("tail", path);
|
||||
return HandlerType::Handler(idx);
|
||||
}
|
||||
}
|
||||
@ -147,11 +144,21 @@ impl<S: 'static> HttpHandler for HttpApplication<S> {
|
||||
|| path.split_at(self.prefix_len).1.starts_with('/'))
|
||||
};
|
||||
if m {
|
||||
let mut req = req.with_state(Rc::clone(&self.state), self.router.clone());
|
||||
let tp = self.get_handler(&mut req);
|
||||
let mut req2 =
|
||||
req.clone_with_state(Rc::clone(&self.state), self.router.clone());
|
||||
|
||||
if let Some(ref filters) = self.filters {
|
||||
for filter in filters {
|
||||
if !filter.check(&mut req2) {
|
||||
return Err(req);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let tp = self.get_handler(&mut req2);
|
||||
let inner = Rc::clone(&self.inner);
|
||||
Ok(Box::new(Pipeline::new(
|
||||
req,
|
||||
req2,
|
||||
Rc::clone(&self.middlewares),
|
||||
inner,
|
||||
tp,
|
||||
@ -172,6 +179,7 @@ struct ApplicationParts<S> {
|
||||
external: HashMap<String, Resource>,
|
||||
encoding: ContentEncoding,
|
||||
middlewares: Vec<Box<Middleware<S>>>,
|
||||
filters: Vec<Box<Predicate<S>>>,
|
||||
}
|
||||
|
||||
/// Structure that follows the builder pattern for building application
|
||||
@ -194,6 +202,7 @@ impl App<()> {
|
||||
handlers: Vec::new(),
|
||||
external: HashMap::new(),
|
||||
encoding: ContentEncoding::Auto,
|
||||
filters: Vec::new(),
|
||||
middlewares: Vec::new(),
|
||||
}),
|
||||
}
|
||||
@ -233,6 +242,7 @@ where
|
||||
handlers: Vec::new(),
|
||||
external: HashMap::new(),
|
||||
middlewares: Vec::new(),
|
||||
filters: Vec::new(),
|
||||
encoding: ContentEncoding::Auto,
|
||||
}),
|
||||
}
|
||||
@ -271,8 +281,8 @@ where
|
||||
/// let app = App::new()
|
||||
/// .prefix("/app")
|
||||
/// .resource("/test", |r| {
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// })
|
||||
/// .finish();
|
||||
/// }
|
||||
@ -289,6 +299,26 @@ where
|
||||
self
|
||||
}
|
||||
|
||||
/// Add match predicate to application.
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// # use actix_web::*;
|
||||
/// # fn main() {
|
||||
/// App::new()
|
||||
/// .filter(pred::Host("www.rust-lang.org"))
|
||||
/// .resource("/path", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// # .finish();
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn filter<T: Predicate<S> + 'static>(mut self, p: T) -> App<S> {
|
||||
{
|
||||
let parts = self.parts.as_mut().expect("Use after finish");
|
||||
parts.filters.push(Box::new(p));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Configure route for a specific path.
|
||||
///
|
||||
/// This is a simplified version of the `App::resource()` method.
|
||||
@ -304,10 +334,12 @@ where
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .route("/test", http::Method::GET,
|
||||
/// |_: HttpRequest| HttpResponse::Ok())
|
||||
/// .route("/test", http::Method::POST,
|
||||
/// |_: HttpRequest| HttpResponse::MethodNotAllowed());
|
||||
/// .route("/test", http::Method::GET, |_: HttpRequest| {
|
||||
/// HttpResponse::Ok()
|
||||
/// })
|
||||
/// .route("/test", http::Method::POST, |_: HttpRequest| {
|
||||
/// HttpResponse::MethodNotAllowed()
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn route<T, F, R>(mut self, path: &str, method: Method, f: F) -> App<S>
|
||||
@ -349,12 +381,12 @@ where
|
||||
/// use actix_web::{http, App, HttpRequest, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .scope("/{project_id}", |scope| {
|
||||
/// scope.resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path2", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed()))
|
||||
/// });
|
||||
/// let app = App::new().scope("/{project_id}", |scope| {
|
||||
/// scope
|
||||
/// .resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path2", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed()))
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@ -369,14 +401,6 @@ where
|
||||
{
|
||||
{
|
||||
let mut scope = Box::new(f(Scope::new()));
|
||||
|
||||
let mut path = path.trim().trim_right_matches('/').to_owned();
|
||||
if !path.is_empty() && !path.starts_with('/') {
|
||||
path.insert(0, '/')
|
||||
}
|
||||
if !path.ends_with('/') {
|
||||
path.push('/');
|
||||
}
|
||||
let parts = self.parts.as_mut().expect("Use after finish");
|
||||
|
||||
let filters = scope.take_filters();
|
||||
@ -414,11 +438,10 @@ where
|
||||
/// use actix_web::{http, App, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .resource("/users/{userid}/{friend}", |r| {
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// });
|
||||
/// let app = App::new().resource("/users/{userid}/{friend}", |r| {
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn resource<F, R>(mut self, path: &str, f: F) -> App<S>
|
||||
@ -481,9 +504,9 @@ where
|
||||
/// use actix_web::{App, HttpRequest, HttpResponse, Result};
|
||||
///
|
||||
/// fn index(mut req: HttpRequest) -> Result<HttpResponse> {
|
||||
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
|
||||
/// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
|
||||
/// Ok(HttpResponse::Ok().into())
|
||||
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
|
||||
/// assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
|
||||
/// Ok(HttpResponse::Ok().into())
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
@ -526,13 +549,11 @@ where
|
||||
/// use actix_web::{http, App, HttpRequest, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .handler("/app", |req: HttpRequest| {
|
||||
/// match *req.method() {
|
||||
/// http::Method::GET => HttpResponse::Ok(),
|
||||
/// http::Method::POST => HttpResponse::MethodNotAllowed(),
|
||||
/// _ => HttpResponse::NotFound(),
|
||||
/// }});
|
||||
/// let app = App::new().handler("/app", |req: HttpRequest| match *req.method() {
|
||||
/// http::Method::GET => HttpResponse::Ok(),
|
||||
/// http::Method::POST => HttpResponse::MethodNotAllowed(),
|
||||
/// _ => HttpResponse::NotFound(),
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn handler<H: Handler<S>>(mut self, path: &str, handler: H) -> App<S> {
|
||||
@ -573,15 +594,14 @@ where
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::{App, HttpResponse, fs, middleware};
|
||||
/// use actix_web::{fs, middleware, App, HttpResponse};
|
||||
///
|
||||
/// // this function could be located in different module
|
||||
/// fn config(app: App) -> App {
|
||||
/// app
|
||||
/// .resource("/test", |r| {
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// })
|
||||
/// app.resource("/test", |r| {
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// })
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
@ -622,6 +642,11 @@ where
|
||||
handlers: parts.handlers,
|
||||
resources,
|
||||
}));
|
||||
let filters = if parts.filters.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parts.filters)
|
||||
};
|
||||
|
||||
HttpApplication {
|
||||
state: Rc::new(parts.state),
|
||||
@ -630,6 +655,7 @@ where
|
||||
prefix,
|
||||
prefix_len,
|
||||
inner,
|
||||
filters,
|
||||
}
|
||||
}
|
||||
|
||||
@ -648,19 +674,22 @@ where
|
||||
/// struct State2;
|
||||
///
|
||||
/// fn main() {
|
||||
/// # thread::spawn(|| {
|
||||
/// server::new(|| { vec![
|
||||
/// App::with_state(State1)
|
||||
/// .prefix("/app1")
|
||||
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
|
||||
/// .boxed(),
|
||||
/// App::with_state(State2)
|
||||
/// .prefix("/app2")
|
||||
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
|
||||
/// .boxed() ]})
|
||||
/// .bind("127.0.0.1:8080").unwrap()
|
||||
/// # thread::spawn(|| {
|
||||
/// server::new(|| {
|
||||
/// vec![
|
||||
/// App::with_state(State1)
|
||||
/// .prefix("/app1")
|
||||
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
|
||||
/// .boxed(),
|
||||
/// App::with_state(State2)
|
||||
/// .prefix("/app2")
|
||||
/// .resource("/", |r| r.f(|r| HttpResponse::Ok()))
|
||||
/// .boxed(),
|
||||
/// ]
|
||||
/// }).bind("127.0.0.1:8080")
|
||||
/// .unwrap()
|
||||
/// .run()
|
||||
/// # });
|
||||
/// # });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn boxed(mut self) -> Box<HttpHandler> {
|
||||
@ -711,7 +740,8 @@ mod tests {
|
||||
use http::StatusCode;
|
||||
use httprequest::HttpRequest;
|
||||
use httpresponse::HttpResponse;
|
||||
use test::TestRequest;
|
||||
use pred;
|
||||
use test::{TestRequest, TestServer};
|
||||
|
||||
#[test]
|
||||
fn test_default_resource() {
|
||||
@ -910,4 +940,21 @@ mod tests {
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter() {
|
||||
let mut srv = TestServer::with_factory(|| {
|
||||
App::new()
|
||||
.filter(pred::Get())
|
||||
.handler("/test", |_| HttpResponse::Ok())
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let request = srv.post().uri(srv.url("/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
@ -9,8 +9,8 @@ use actix::actors::{Connect as ResolveConnect, Connector, ConnectorError};
|
||||
use actix::fut::WrapFuture;
|
||||
use actix::registry::ArbiterService;
|
||||
use actix::{
|
||||
fut, Actor, ActorFuture, ActorResponse, Arbiter, AsyncContext, Context,
|
||||
ContextFutureSpawner, Handler, Message, Recipient, Supervised, Syn,
|
||||
fut, Actor, ActorFuture, ActorResponse, Addr, Arbiter, AsyncContext, Context,
|
||||
ContextFutureSpawner, Handler, Message, Recipient, Supervised, Syn, Unsync,
|
||||
};
|
||||
|
||||
use futures::task::{current as current_task, Task};
|
||||
@ -181,6 +181,7 @@ pub struct ClientConnector {
|
||||
pool: Rc<Pool>,
|
||||
pool_modified: Rc<Cell<bool>>,
|
||||
|
||||
resolver: Addr<Unsync, Connector>,
|
||||
conn_lifetime: Duration,
|
||||
conn_keep_alive: Duration,
|
||||
limit: usize,
|
||||
@ -225,6 +226,7 @@ impl Default for ClientConnector {
|
||||
pool: Rc::new(Pool::new(Rc::clone(&_modified))),
|
||||
pool_modified: _modified,
|
||||
connector: builder.build().unwrap(),
|
||||
resolver: Connector::from_registry(),
|
||||
conn_lifetime: Duration::from_secs(75),
|
||||
conn_keep_alive: Duration::from_secs(15),
|
||||
limit: 100,
|
||||
@ -245,6 +247,7 @@ impl Default for ClientConnector {
|
||||
subscriber: None,
|
||||
pool: Rc::new(Pool::new(Rc::clone(&_modified))),
|
||||
pool_modified: _modified,
|
||||
resolver: Connector::from_registry(),
|
||||
conn_lifetime: Duration::from_secs(75),
|
||||
conn_keep_alive: Duration::from_secs(15),
|
||||
limit: 100,
|
||||
@ -277,9 +280,9 @@ impl ClientConnector {
|
||||
/// # use std::io::Write;
|
||||
/// extern crate openssl;
|
||||
/// use actix::prelude::*;
|
||||
/// use actix_web::client::{Connect, ClientConnector};
|
||||
/// use actix_web::client::{ClientConnector, Connect};
|
||||
///
|
||||
/// use openssl::ssl::{SslMethod, SslConnector};
|
||||
/// use openssl::ssl::{SslConnector, SslMethod};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let sys = System::new("test");
|
||||
@ -312,6 +315,7 @@ impl ClientConnector {
|
||||
subscriber: None,
|
||||
pool: Rc::new(Pool::new(Rc::clone(&modified))),
|
||||
pool_modified: modified,
|
||||
resolver: Connector::from_registry(),
|
||||
conn_lifetime: Duration::from_secs(75),
|
||||
conn_keep_alive: Duration::from_secs(15),
|
||||
limit: 100,
|
||||
@ -371,6 +375,12 @@ impl ClientConnector {
|
||||
self
|
||||
}
|
||||
|
||||
/// Use custom resolver actor
|
||||
pub fn resolver(mut self, addr: Addr<Unsync, Connector>) -> Self {
|
||||
self.resolver = addr;
|
||||
self
|
||||
}
|
||||
|
||||
fn acquire(&mut self, key: &Key) -> Acquire {
|
||||
// check limits
|
||||
if self.limit > 0 {
|
||||
@ -705,7 +715,7 @@ impl Handler<Connect> for ClientConnector {
|
||||
|
||||
{
|
||||
ActorResponse::async(
|
||||
Connector::from_registry()
|
||||
self.resolver
|
||||
.send(
|
||||
ResolveConnect::host_and_port(&conn.0.host, port)
|
||||
.timeout(conn_timeout),
|
||||
@ -855,7 +865,7 @@ impl fut::ActorFuture for Maintenance {
|
||||
let conn = AcquiredConn(key.clone(), Some(Rc::clone(&act.pool)));
|
||||
|
||||
fut::WrapFuture::<ClientConnector>::actfuture(
|
||||
Connector::from_registry().send(
|
||||
act.resolver.send(
|
||||
ResolveConnect::host_and_port(&conn.0.host, conn.0.port)
|
||||
.timeout(waiter.conn_timeout),
|
||||
),
|
||||
|
@ -380,7 +380,7 @@ impl Pipeline {
|
||||
match self.timeout.as_mut().unwrap().poll() {
|
||||
Ok(Async::Ready(())) => return Err(SendRequestError::Timeout),
|
||||
Ok(Async::NotReady) => (),
|
||||
Err(_) => unreachable!(),
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
158
src/error.rs
158
src/error.rs
@ -1,9 +1,9 @@
|
||||
//! Error and Result module
|
||||
use std::cell::RefCell;
|
||||
use std::io::Error as IoError;
|
||||
use std::str::Utf8Error;
|
||||
use std::string::FromUtf8Error;
|
||||
use std::{fmt, io, result};
|
||||
use std::sync::Mutex;
|
||||
use std::{fmt, io, mem, result};
|
||||
|
||||
use actix::MailboxError;
|
||||
use cookie;
|
||||
@ -21,9 +21,10 @@ pub use url::ParseError as UrlParseError;
|
||||
// re-exports
|
||||
pub use cookie::ParseError as CookieParseError;
|
||||
|
||||
use body::Body;
|
||||
use handler::Responder;
|
||||
use httprequest::HttpRequest;
|
||||
use httpresponse::HttpResponse;
|
||||
use httpresponse::{HttpResponse, InnerHttpResponse};
|
||||
|
||||
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
|
||||
/// for actix web operations
|
||||
@ -33,21 +34,44 @@ use httpresponse::HttpResponse;
|
||||
/// `Result`.
|
||||
pub type Result<T, E = Error> = result::Result<T, E>;
|
||||
|
||||
/// General purpose actix web error
|
||||
/// General purpose actix web error.
|
||||
///
|
||||
/// An actix web error is used to carry errors from `failure` or `std::error`
|
||||
/// through actix in a convenient way. It can be created through through
|
||||
/// converting errors with `into()`.
|
||||
///
|
||||
/// Whenever it is created from an external object a response error is created
|
||||
/// for it that can be used to create an http response from it this means that
|
||||
/// if you have access to an actix `Error` you can always get a
|
||||
/// `ResponseError` reference from it.
|
||||
pub struct Error {
|
||||
cause: Box<ResponseError>,
|
||||
backtrace: Option<Backtrace>,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Returns a reference to the underlying cause of this Error.
|
||||
// this should return &Fail but needs this https://github.com/rust-lang/rust/issues/5665
|
||||
/// Deprecated way to reference the underlying response error.
|
||||
#[deprecated(
|
||||
since = "0.6.0", note = "please use `Error::as_response_error()` instead"
|
||||
)]
|
||||
pub fn cause(&self) -> &ResponseError {
|
||||
self.cause.as_ref()
|
||||
}
|
||||
|
||||
/// Returns a reference to the underlying cause of this `Error` as `Fail`
|
||||
pub fn as_fail(&self) -> &Fail {
|
||||
self.cause.as_fail()
|
||||
}
|
||||
|
||||
/// Returns the reference to the underlying `ResponseError`.
|
||||
pub fn as_response_error(&self) -> &ResponseError {
|
||||
self.cause.as_ref()
|
||||
}
|
||||
|
||||
/// Returns a reference to the Backtrace carried by this error, if it
|
||||
/// carries one.
|
||||
///
|
||||
/// This uses the same `Backtrace` type that `failure` uses.
|
||||
pub fn backtrace(&self) -> &Backtrace {
|
||||
if let Some(bt) = self.cause.backtrace() {
|
||||
bt
|
||||
@ -55,10 +79,65 @@ impl Error {
|
||||
self.backtrace.as_ref().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to downcast this `Error` to a particular `Fail` type by
|
||||
/// reference.
|
||||
///
|
||||
/// If the underlying error is not of type `T`, this will return `None`.
|
||||
pub fn downcast_ref<T: Fail>(&self) -> Option<&T> {
|
||||
// in the most trivial way the cause is directly of the requested type.
|
||||
if let Some(rv) = Fail::downcast_ref(self.cause.as_fail()) {
|
||||
return Some(rv);
|
||||
}
|
||||
|
||||
// in the more complex case the error has been constructed from a failure
|
||||
// error. This happens because we implement From<failure::Error> by
|
||||
// calling compat() and then storing it here. In failure this is
|
||||
// represented by a failure::Error being wrapped in a failure::Compat.
|
||||
//
|
||||
// So we first downcast into that compat, to then further downcast through
|
||||
// the failure's Error downcasting system into the original failure.
|
||||
//
|
||||
// This currently requires a transmute. This could be avoided if failure
|
||||
// provides a deref: https://github.com/rust-lang-nursery/failure/pull/213
|
||||
let compat: Option<&failure::Compat<failure::Error>> =
|
||||
Fail::downcast_ref(self.cause.as_fail());
|
||||
if let Some(compat) = compat {
|
||||
pub struct CompatWrappedError {
|
||||
error: failure::Error,
|
||||
}
|
||||
let compat: &CompatWrappedError = unsafe { ::std::mem::transmute(compat) };
|
||||
compat.error.downcast_ref()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper trait to downcast a response error into a fail.
|
||||
///
|
||||
/// This is currently not exposed because it's unclear if this is the best way
|
||||
/// to achieve the downcasting on `Error` for which this is needed.
|
||||
#[doc(hidden)]
|
||||
pub trait InternalResponseErrorAsFail {
|
||||
#[doc(hidden)]
|
||||
fn as_fail(&self) -> &Fail;
|
||||
#[doc(hidden)]
|
||||
fn as_mut_fail(&mut self) -> &mut Fail;
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
impl<T: ResponseError> InternalResponseErrorAsFail for T {
|
||||
fn as_fail(&self) -> &Fail {
|
||||
self
|
||||
}
|
||||
fn as_mut_fail(&mut self) -> &mut Fail {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Error that can be converted to `HttpResponse`
|
||||
pub trait ResponseError: Fail {
|
||||
pub trait ResponseError: Fail + InternalResponseErrorAsFail {
|
||||
/// Create response for error
|
||||
///
|
||||
/// Internal server error is generated by default.
|
||||
@ -111,11 +190,9 @@ impl<T: ResponseError> From<T> for Error {
|
||||
}
|
||||
|
||||
/// Compatibility for `failure::Error`
|
||||
impl<T> ResponseError for failure::Compat<T>
|
||||
where
|
||||
T: fmt::Display + fmt::Debug + Sync + Send + 'static,
|
||||
{
|
||||
}
|
||||
impl<T> ResponseError for failure::Compat<T> where
|
||||
T: fmt::Display + fmt::Debug + Sync + Send + 'static
|
||||
{}
|
||||
|
||||
impl From<failure::Error> for Error {
|
||||
fn from(err: failure::Error) -> Error {
|
||||
@ -548,8 +625,8 @@ impl From<UrlParseError> for UrlGenerationError {
|
||||
/// use actix_web::fs::NamedFile;
|
||||
///
|
||||
/// fn index(req: HttpRequest) -> Result<fs::NamedFile> {
|
||||
/// let f = NamedFile::open("test.txt").map_err(error::ErrorBadRequest)?;
|
||||
/// Ok(f)
|
||||
/// let f = NamedFile::open("test.txt").map_err(error::ErrorBadRequest)?;
|
||||
/// Ok(f)
|
||||
/// }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
@ -559,12 +636,9 @@ pub struct InternalError<T> {
|
||||
backtrace: Backtrace,
|
||||
}
|
||||
|
||||
unsafe impl<T> Sync for InternalError<T> {}
|
||||
unsafe impl<T> Send for InternalError<T> {}
|
||||
|
||||
enum InternalErrorType {
|
||||
Status(StatusCode),
|
||||
Response(RefCell<Option<HttpResponse>>),
|
||||
Response(Mutex<Option<Box<InnerHttpResponse>>>),
|
||||
}
|
||||
|
||||
impl<T> InternalError<T> {
|
||||
@ -579,9 +653,21 @@ impl<T> InternalError<T> {
|
||||
|
||||
/// Create `InternalError` with predefined `HttpResponse`.
|
||||
pub fn from_response(cause: T, response: HttpResponse) -> Self {
|
||||
let mut resp = response.into_inner();
|
||||
let body = mem::replace(&mut resp.body, Body::Empty);
|
||||
match body {
|
||||
Body::Empty => (),
|
||||
Body::Binary(mut bin) => {
|
||||
resp.body = Body::Binary(bin.take().into());
|
||||
}
|
||||
Body::Streaming(_) | Body::Actor(_) => {
|
||||
error!("Streaming or Actor body is not support by error response");
|
||||
}
|
||||
}
|
||||
|
||||
InternalError {
|
||||
cause,
|
||||
status: InternalErrorType::Response(RefCell::new(Some(response))),
|
||||
status: InternalErrorType::Response(Mutex::new(Some(resp))),
|
||||
backtrace: Backtrace::new(),
|
||||
}
|
||||
}
|
||||
@ -622,8 +708,8 @@ where
|
||||
match self.status {
|
||||
InternalErrorType::Status(st) => HttpResponse::new(st),
|
||||
InternalErrorType::Response(ref resp) => {
|
||||
if let Some(resp) = resp.borrow_mut().take() {
|
||||
resp
|
||||
if let Some(resp) = resp.lock().unwrap().take() {
|
||||
HttpResponse::from_inner(resp)
|
||||
} else {
|
||||
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
@ -833,7 +919,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cause() {
|
||||
fn test_as_fail() {
|
||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||
let desc = orig.description().to_owned();
|
||||
let e = ParseError::Io(orig);
|
||||
@ -851,7 +937,7 @@ mod tests {
|
||||
let orig = io::Error::new(io::ErrorKind::Other, "other");
|
||||
let desc = orig.description().to_owned();
|
||||
let e = Error::from(orig);
|
||||
assert_eq!(format!("{}", e.cause()), desc);
|
||||
assert_eq!(format!("{}", e.as_fail()), desc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -950,6 +1036,32 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_downcasting_direct() {
|
||||
#[derive(Debug, Fail)]
|
||||
#[fail(display = "demo error")]
|
||||
struct DemoError;
|
||||
|
||||
impl ResponseError for DemoError {}
|
||||
|
||||
let err: Error = DemoError.into();
|
||||
let err_ref: &DemoError = err.downcast_ref().unwrap();
|
||||
assert_eq!(err_ref.to_string(), "demo error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_downcasting_compat() {
|
||||
#[derive(Debug, Fail)]
|
||||
#[fail(display = "demo error")]
|
||||
struct DemoError;
|
||||
|
||||
impl ResponseError for DemoError {}
|
||||
|
||||
let err: Error = failure::Error::from(DemoError).into();
|
||||
let err_ref: &DemoError = err.downcast_ref().unwrap();
|
||||
assert_eq!(err_ref.to_string(), "demo error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_helpers() {
|
||||
let r: HttpResponse = ErrorBadRequest("err").into();
|
||||
|
175
src/fs.rs
175
src/fs.rs
@ -20,7 +20,7 @@ use mime_guess::{get_mime_type, guess_mime_type};
|
||||
use error::Error;
|
||||
use handler::{AsyncResult, Handler, Responder, RouteHandler, WrapHandler};
|
||||
use header;
|
||||
use http::{HttpRange, Method, StatusCode};
|
||||
use http::{ContentEncoding, HttpRange, Method, StatusCode};
|
||||
use httpmessage::HttpMessage;
|
||||
use httprequest::HttpRequest;
|
||||
use httpresponse::HttpResponse;
|
||||
@ -38,6 +38,7 @@ pub struct NamedFile {
|
||||
md: Metadata,
|
||||
modified: Option<SystemTime>,
|
||||
cpu_pool: Option<CpuPool>,
|
||||
encoding: Option<ContentEncoding>,
|
||||
only_get: bool,
|
||||
status_code: StatusCode,
|
||||
}
|
||||
@ -58,12 +59,14 @@ impl NamedFile {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let modified = md.modified().ok();
|
||||
let cpu_pool = None;
|
||||
let encoding = None;
|
||||
Ok(NamedFile {
|
||||
path,
|
||||
file,
|
||||
md,
|
||||
modified,
|
||||
cpu_pool,
|
||||
encoding,
|
||||
only_get: false,
|
||||
status_code: StatusCode::OK,
|
||||
})
|
||||
@ -114,6 +117,13 @@ impl NamedFile {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set content encoding for serving this file
|
||||
#[inline]
|
||||
pub fn set_content_encoding(mut self, enc: ContentEncoding) -> Self {
|
||||
self.encoding = Some(enc);
|
||||
self
|
||||
}
|
||||
|
||||
fn etag(&self) -> Option<header::EntityTag> {
|
||||
// This etag format is similar to Apache's.
|
||||
self.modified.as_ref().map(|mtime| {
|
||||
@ -219,6 +229,9 @@ impl Responder for NamedFile {
|
||||
),
|
||||
);
|
||||
});
|
||||
if let Some(current_encoding) = self.encoding {
|
||||
resp.content_encoding(current_encoding);
|
||||
}
|
||||
let reader = ChunkedReadFile {
|
||||
size: self.md.len(),
|
||||
offset: 0,
|
||||
@ -264,6 +277,9 @@ impl Responder for NamedFile {
|
||||
};
|
||||
|
||||
let mut resp = HttpResponse::build(self.status_code);
|
||||
if let Some(current_encoding) = self.encoding {
|
||||
resp.content_encoding(current_encoding);
|
||||
}
|
||||
|
||||
resp.if_some(self.path().extension(), |ext, resp| {
|
||||
resp.set(header::ContentType(get_mime_type(&ext.to_string_lossy())));
|
||||
@ -289,30 +305,29 @@ impl Responder for NamedFile {
|
||||
resp.set(header::ETag(etag));
|
||||
});
|
||||
|
||||
// TODO: Debug, enabling "accept-ranges: bytes" causes problems with
|
||||
// certain clients when not using the ranges header.
|
||||
//resp.header(header::ACCEPT_RANGES, format!("bytes"));
|
||||
resp.header(header::ACCEPT_RANGES, "bytes");
|
||||
|
||||
let mut length = self.md.len();
|
||||
let mut offset = 0;
|
||||
|
||||
// check for ranges header
|
||||
// check for range header
|
||||
if let Some(ranges) = req.headers().get(header::RANGE) {
|
||||
if let Ok(rangesheader) = ranges.to_str() {
|
||||
if let Ok(rangesvec) = HttpRange::parse(rangesheader, length) {
|
||||
length = rangesvec[0].length - 1;
|
||||
length = rangesvec[0].length;
|
||||
offset = rangesvec[0].start;
|
||||
resp.content_encoding(ContentEncoding::Identity);
|
||||
resp.header(
|
||||
header::RANGE,
|
||||
header::CONTENT_RANGE,
|
||||
format!(
|
||||
"bytes={}-{}/{}",
|
||||
"bytes {}-{}/{}",
|
||||
offset,
|
||||
offset + length,
|
||||
offset + length - 1,
|
||||
self.md.len()
|
||||
),
|
||||
);
|
||||
} else {
|
||||
resp.header(header::RANGE, format!("*/{}", length));
|
||||
resp.header(header::CONTENT_RANGE, format!("bytes */{}", length));
|
||||
return Ok(resp.status(StatusCode::RANGE_NOT_SATISFIABLE).finish());
|
||||
};
|
||||
} else {
|
||||
@ -638,10 +653,6 @@ impl<S: 'static> Handler<S> for StaticFiles<S> {
|
||||
// TODO: It'd be nice if there were a good usable URL manipulation
|
||||
// library
|
||||
let mut new_path: String = req.path().to_owned();
|
||||
for el in relpath.iter() {
|
||||
new_path.push_str(&el.to_string_lossy());
|
||||
new_path.push('/');
|
||||
}
|
||||
if !new_path.ends_with('/') {
|
||||
new_path.push('/');
|
||||
}
|
||||
@ -778,6 +789,7 @@ mod tests {
|
||||
App::new().handler("test", StaticFiles::new(".").index_file("Cargo.toml"))
|
||||
});
|
||||
|
||||
// Valid range header
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/Cargo.toml"))
|
||||
@ -787,10 +799,21 @@ mod tests {
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
|
||||
|
||||
// Invalid range header
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/Cargo.toml"))
|
||||
.header(header::RANGE, "bytes=1-0")
|
||||
.finish()
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_ranges_headers() {
|
||||
fn test_named_file_content_range_headers() {
|
||||
let mut srv = test::TestServer::with_factory(|| {
|
||||
App::new().handler(
|
||||
"test",
|
||||
@ -798,13 +821,64 @@ mod tests {
|
||||
)
|
||||
});
|
||||
|
||||
// Valid range header
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/tests/test.binary"))
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.finish()
|
||||
.unwrap();
|
||||
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
let contentrange = response
|
||||
.headers()
|
||||
.get(header::CONTENT_RANGE)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contentrange, "bytes 10-20/100");
|
||||
|
||||
// Invalid range header
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/tests/test.binary"))
|
||||
.header(header::RANGE, "bytes=10-5")
|
||||
.finish()
|
||||
.unwrap();
|
||||
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
let contentrange = response
|
||||
.headers()
|
||||
.get(header::CONTENT_RANGE)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contentrange, "bytes */100");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_content_length_headers() {
|
||||
let mut srv = test::TestServer::with_factory(|| {
|
||||
App::new().handler(
|
||||
"test",
|
||||
StaticFiles::new(".").index_file("tests/test.binary"),
|
||||
)
|
||||
});
|
||||
|
||||
// Valid range header
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/tests/test.binary"))
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.finish()
|
||||
.unwrap();
|
||||
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
.get(header::CONTENT_LENGTH)
|
||||
@ -812,23 +886,62 @@ mod tests {
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contentlength, "10");
|
||||
assert_eq!(contentlength, "11");
|
||||
|
||||
// Invalid range header
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/tests/test.binary"))
|
||||
.header(header::RANGE, "bytes=10-20")
|
||||
.header(header::RANGE, "bytes=10-8")
|
||||
.finish()
|
||||
.unwrap();
|
||||
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
let range = response
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
.get(header::RANGE)
|
||||
.get(header::CONTENT_LENGTH)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(range, "bytes=10-20/100");
|
||||
assert_eq!(contentlength, "0");
|
||||
|
||||
// Without range header
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/tests/test.binary"))
|
||||
.no_default_headers()
|
||||
.finish()
|
||||
.unwrap();
|
||||
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
let contentlength = response
|
||||
.headers()
|
||||
.get(header::CONTENT_LENGTH)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(contentlength, "100");
|
||||
|
||||
// chunked
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/t%65st/tests/test.binary"))
|
||||
.finish()
|
||||
.unwrap();
|
||||
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
let te = response
|
||||
.headers()
|
||||
.get(header::TRANSFER_ENCODING)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
assert_eq!(te, "chunked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -840,6 +953,21 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_content_encoding() {
|
||||
let req = TestRequest::default().method(Method::GET).finish();
|
||||
let file = NamedFile::open("Cargo.toml").unwrap();
|
||||
|
||||
assert!(file.encoding.is_none());
|
||||
let resp = file
|
||||
.set_content_encoding(ContentEncoding::Identity)
|
||||
.respond_to(&req)
|
||||
.unwrap();
|
||||
|
||||
assert!(resp.content_encoding().is_some());
|
||||
assert_eq!(resp.content_encoding().unwrap().as_str(), "identity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_named_file_any_method() {
|
||||
let req = TestRequest::default().method(Method::POST).finish();
|
||||
@ -885,7 +1013,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_redirect_to_index() {
|
||||
let mut st = StaticFiles::new(".").index_file("index.html");
|
||||
let mut req = HttpRequest::default();
|
||||
let mut req = TestRequest::default().uri("/tests").finish();
|
||||
|
||||
req.match_info_mut().add("tail", "tests");
|
||||
|
||||
let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap();
|
||||
@ -896,7 +1025,7 @@ mod tests {
|
||||
"/tests/index.html"
|
||||
);
|
||||
|
||||
let mut req = HttpRequest::default();
|
||||
let mut req = TestRequest::default().uri("/tests/").finish();
|
||||
req.match_info_mut().add("tail", "tests/");
|
||||
|
||||
let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap();
|
||||
@ -911,7 +1040,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_redirect_to_index_nested() {
|
||||
let mut st = StaticFiles::new(".").index_file("Cargo.toml");
|
||||
let mut req = HttpRequest::default();
|
||||
let mut req = TestRequest::default().uri("/tools/wsload").finish();
|
||||
req.match_info_mut().add("tail", "tools/wsload");
|
||||
|
||||
let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap();
|
||||
|
@ -148,7 +148,6 @@ pub trait HttpMessage {
|
||||
/// Returns error:
|
||||
///
|
||||
/// * content type is not `application/x-www-form-urlencoded`
|
||||
/// * transfer encoding is `chunked`.
|
||||
/// * content-length is greater than 256k
|
||||
///
|
||||
/// ## Server example
|
||||
@ -365,9 +364,7 @@ where
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(req) = self.req.take() {
|
||||
if req.chunked().unwrap_or(false) {
|
||||
return Err(UrlencodedError::Chunked);
|
||||
} else if let Some(len) = req.headers().get(header::CONTENT_LENGTH) {
|
||||
if let Some(len) = req.headers().get(header::CONTENT_LENGTH) {
|
||||
if let Ok(s) = len.to_str() {
|
||||
if let Ok(len) = s.parse::<u64>() {
|
||||
if len > 262_144 {
|
||||
@ -575,13 +572,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_urlencoded_error() {
|
||||
let req =
|
||||
TestRequest::with_header(header::TRANSFER_ENCODING, "chunked").finish();
|
||||
assert_eq!(
|
||||
req.urlencoded::<Info>().poll().err().unwrap(),
|
||||
UrlencodedError::Chunked
|
||||
);
|
||||
|
||||
let req = TestRequest::with_header(
|
||||
header::CONTENT_TYPE,
|
||||
"application/x-www-form-urlencoded",
|
||||
|
@ -141,6 +141,12 @@ impl HttpRequest<()> {
|
||||
pub fn with_state<S>(self, state: Rc<S>, router: Router) -> HttpRequest<S> {
|
||||
HttpRequest(self.0, Some(state), Some(router))
|
||||
}
|
||||
|
||||
pub(crate) fn clone_with_state<S>(
|
||||
&self, state: Rc<S>, router: Router,
|
||||
) -> HttpRequest<S> {
|
||||
HttpRequest(self.0.clone(), Some(state), Some(router))
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> HttpMessage for HttpRequest<S> {
|
||||
@ -325,6 +331,15 @@ impl<S> HttpRequest<S> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate url for named resource
|
||||
///
|
||||
/// This method is similar to `HttpRequest::url_for()` but it can be used
|
||||
/// for urls that do not contain variable parts.
|
||||
pub fn url_for_static(&self, name: &str) -> Result<Url, UrlGenerationError> {
|
||||
const NO_PARAMS: [&str; 0] = [];
|
||||
self.url_for(name, &NO_PARAMS)
|
||||
}
|
||||
|
||||
/// This method returns reference to current `Router` object.
|
||||
#[inline]
|
||||
pub fn router(&self) -> Option<&Router> {
|
||||
@ -695,20 +710,38 @@ mod tests {
|
||||
|
||||
let mut resource = ResourceHandler::<()>::default();
|
||||
resource.name("index");
|
||||
let routes =
|
||||
vec![(Resource::new("index", "/user/{name}.{ext}"), Some(resource))];
|
||||
let routes = vec![(Resource::new("index", "/user/{name}.html"), Some(resource))];
|
||||
let (router, _) = Router::new("/prefix/", ServerSettings::default(), routes);
|
||||
assert!(router.has_route("/user/test.html"));
|
||||
assert!(!router.has_route("/prefix/user/test.html"));
|
||||
|
||||
let req = req.with_state(Rc::new(()), router);
|
||||
let url = req.url_for("index", &["test", "html"]);
|
||||
let url = req.url_for("index", &["test"]);
|
||||
assert_eq!(
|
||||
url.ok().unwrap().as_str(),
|
||||
"http://www.rust-lang.org/prefix/user/test.html"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_url_for_static() {
|
||||
let req = TestRequest::with_header(header::HOST, "www.rust-lang.org").finish();
|
||||
|
||||
let mut resource = ResourceHandler::<()>::default();
|
||||
resource.name("index");
|
||||
let routes = vec![(Resource::new("index", "/index.html"), Some(resource))];
|
||||
let (router, _) = Router::new("/prefix/", ServerSettings::default(), routes);
|
||||
assert!(router.has_route("/index.html"));
|
||||
assert!(!router.has_route("/prefix/index.html"));
|
||||
|
||||
let req = req.with_state(Rc::new(()), router);
|
||||
let url = req.url_for_static("index");
|
||||
assert_eq!(
|
||||
url.ok().unwrap().as_str(),
|
||||
"http://www.rust-lang.org/prefix/index.html"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_url_for_external() {
|
||||
let req = HttpRequest::default();
|
||||
|
@ -89,7 +89,7 @@ impl HttpResponse {
|
||||
/// Constructs a error response
|
||||
#[inline]
|
||||
pub fn from_error(error: Error) -> HttpResponse {
|
||||
let mut resp = error.cause().error_response();
|
||||
let mut resp = error.as_response_error().error_response();
|
||||
resp.get_mut().error = Some(error);
|
||||
resp
|
||||
}
|
||||
@ -241,6 +241,14 @@ impl HttpResponse {
|
||||
pub fn set_write_buffer_capacity(&mut self, cap: usize) {
|
||||
self.get_mut().write_capacity = cap;
|
||||
}
|
||||
|
||||
pub(crate) fn into_inner(mut self) -> Box<InnerHttpResponse> {
|
||||
self.0.take().unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn from_inner(inner: Box<InnerHttpResponse>) -> HttpResponse {
|
||||
HttpResponse(Some(inner), HttpResponsePool::pool())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for HttpResponse {
|
||||
@ -297,11 +305,13 @@ impl HttpResponseBuilder {
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::{HttpRequest, HttpResponse, Result, http};
|
||||
/// use actix_web::{http, HttpRequest, HttpResponse, Result};
|
||||
///
|
||||
/// fn index(req: HttpRequest) -> Result<HttpResponse> {
|
||||
/// Ok(HttpResponse::Ok()
|
||||
/// .set(http::header::IfModifiedSince("Sun, 07 Nov 1994 08:48:37 GMT".parse()?))
|
||||
/// .set(http::header::IfModifiedSince(
|
||||
/// "Sun, 07 Nov 1994 08:48:37 GMT".parse()?,
|
||||
/// ))
|
||||
/// .finish())
|
||||
/// }
|
||||
/// fn main() {}
|
||||
@ -455,7 +465,8 @@ impl HttpResponseBuilder {
|
||||
/// .path("/")
|
||||
/// .secure(true)
|
||||
/// .http_only(true)
|
||||
/// .finish())
|
||||
/// .finish(),
|
||||
/// )
|
||||
/// .finish()
|
||||
/// }
|
||||
/// fn main() {}
|
||||
@ -781,12 +792,12 @@ impl<'a, S> From<&'a HttpRequest<S>> for HttpResponseBuilder {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InnerHttpResponse {
|
||||
pub(crate) struct InnerHttpResponse {
|
||||
version: Option<Version>,
|
||||
headers: HeaderMap,
|
||||
status: StatusCode,
|
||||
reason: Option<&'static str>,
|
||||
body: Body,
|
||||
pub(crate) body: Body,
|
||||
chunked: Option<bool>,
|
||||
encoding: Option<ContentEncoding>,
|
||||
connection_type: Option<ConnectionType>,
|
||||
@ -795,6 +806,9 @@ struct InnerHttpResponse {
|
||||
error: Option<Error>,
|
||||
}
|
||||
|
||||
unsafe impl Sync for InnerHttpResponse {}
|
||||
unsafe impl Send for InnerHttpResponse {}
|
||||
|
||||
impl InnerHttpResponse {
|
||||
#[inline]
|
||||
fn new(status: StatusCode, body: Body) -> InnerHttpResponse {
|
||||
|
13
src/lib.rs
13
src/lib.rs
@ -6,15 +6,15 @@
|
||||
//! # use std::thread;
|
||||
//!
|
||||
//! fn index(info: Path<(String, u32)>) -> String {
|
||||
//! format!("Hello {}! id:{}", info.0, info.1)
|
||||
//! format!("Hello {}! id:{}", info.0, info.1)
|
||||
//! }
|
||||
//!
|
||||
//! fn main() {
|
||||
//! # thread::spawn(|| {
|
||||
//! server::new(
|
||||
//! || App::new()
|
||||
//! .resource("/{name}/{id}/index.html", |r| r.with(index)))
|
||||
//! .bind("127.0.0.1:8080").unwrap()
|
||||
//! server::new(|| {
|
||||
//! App::new().resource("/{name}/{id}/index.html", |r| r.with(index))
|
||||
//! }).bind("127.0.0.1:8080")
|
||||
//! .unwrap()
|
||||
//! .run();
|
||||
//! # });
|
||||
//! }
|
||||
@ -25,7 +25,7 @@
|
||||
//! Besides the API documentation (which you are currently looking
|
||||
//! at!), several other resources are available:
|
||||
//!
|
||||
//! * [User Guide](https://actix.rs/book/actix-web/)
|
||||
//! * [User Guide](https://actix.rs/docs/)
|
||||
//! * [Chat on gitter](https://gitter.im/actix/actix)
|
||||
//! * [GitHub repository](https://github.com/actix/actix-web)
|
||||
//! * [Cargo package](https://crates.io/crates/actix-web)
|
||||
@ -77,6 +77,7 @@
|
||||
//!
|
||||
#![cfg_attr(actix_nightly, feature(
|
||||
specialization, // for impl ErrorResponse for std::error::Error
|
||||
extern_prelude,
|
||||
))]
|
||||
#![cfg_attr(
|
||||
feature = "cargo-clippy",
|
||||
|
@ -19,16 +19,16 @@
|
||||
//!
|
||||
//! ```rust
|
||||
//! # extern crate actix_web;
|
||||
//! use actix_web::{http, App, HttpRequest, HttpResponse};
|
||||
//! use actix_web::middleware::cors::Cors;
|
||||
//! use actix_web::{http, App, HttpRequest, HttpResponse};
|
||||
//!
|
||||
//! fn index(mut req: HttpRequest) -> &'static str {
|
||||
//! "Hello world"
|
||||
//! "Hello world"
|
||||
//! }
|
||||
//!
|
||||
//! fn main() {
|
||||
//! let app = App::new()
|
||||
//! .configure(|app| Cors::for_app(app) // <- Construct CORS middleware builder
|
||||
//! let app = App::new().configure(|app| {
|
||||
//! Cors::for_app(app) // <- Construct CORS middleware builder
|
||||
//! .allowed_origin("https://www.rust-lang.org/")
|
||||
//! .allowed_methods(vec!["GET", "POST"])
|
||||
//! .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
|
||||
@ -38,7 +38,8 @@
|
||||
//! r.method(http::Method::GET).f(|_| HttpResponse::Ok());
|
||||
//! r.method(http::Method::HEAD).f(|_| HttpResponse::MethodNotAllowed());
|
||||
//! })
|
||||
//! .register());
|
||||
//! .register()
|
||||
//! });
|
||||
//! }
|
||||
//! ```
|
||||
//! In this example custom *CORS* middleware get registered for "/index.html"
|
||||
@ -232,18 +233,20 @@ impl Cors {
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::{http, App, HttpResponse};
|
||||
/// use actix_web::middleware::cors::Cors;
|
||||
/// use actix_web::{http, App, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .configure(|app| Cors::for_app(app) // <- Construct CORS builder
|
||||
/// let app = App::new().configure(
|
||||
/// |app| {
|
||||
/// Cors::for_app(app) // <- Construct CORS builder
|
||||
/// .allowed_origin("https://www.rust-lang.org/")
|
||||
/// .resource("/resource", |r| { // register resource
|
||||
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
|
||||
/// })
|
||||
/// .register() // construct CORS and return application instance
|
||||
/// );
|
||||
/// .register()
|
||||
/// }, // construct CORS and return application instance
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
pub fn for_app<S: 'static>(app: App<S>) -> CorsBuilder<S> {
|
||||
@ -420,7 +423,10 @@ impl<S> Middleware<S> for Cors {
|
||||
.finish(),
|
||||
))
|
||||
} else {
|
||||
self.validate_origin(req)?;
|
||||
// Only check requests with a origin header.
|
||||
if req.headers().contains_key(header::ORIGIN) {
|
||||
self.validate_origin(req)?;
|
||||
}
|
||||
|
||||
Ok(Started::Done)
|
||||
}
|
||||
@ -491,8 +497,8 @@ impl<S> Middleware<S> for Cors {
|
||||
/// ```rust
|
||||
/// # extern crate http;
|
||||
/// # extern crate actix_web;
|
||||
/// use http::header;
|
||||
/// use actix_web::middleware::cors;
|
||||
/// use http::header;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let cors = cors::Cors::build()
|
||||
@ -764,12 +770,13 @@ impl<S: 'static> CorsBuilder<S> {
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::{http, App, HttpResponse};
|
||||
/// use actix_web::middleware::cors::Cors;
|
||||
/// use actix_web::{http, App, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .configure(|app| Cors::for_app(app) // <- Construct CORS builder
|
||||
/// let app = App::new().configure(
|
||||
/// |app| {
|
||||
/// Cors::for_app(app) // <- Construct CORS builder
|
||||
/// .allowed_origin("https://www.rust-lang.org/")
|
||||
/// .allowed_methods(vec!["GET", "POST"])
|
||||
/// .allowed_header(http::header::CONTENT_TYPE)
|
||||
@ -781,8 +788,9 @@ impl<S: 'static> CorsBuilder<S> {
|
||||
/// r.method(http::Method::HEAD)
|
||||
/// .f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// })
|
||||
/// .register() // construct CORS and return application instance
|
||||
/// );
|
||||
/// .register()
|
||||
/// }, // construct CORS and return application instance
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
pub fn resource<F, R>(&mut self, path: &str, f: F) -> &mut CorsBuilder<S>
|
||||
@ -1001,16 +1009,15 @@ mod tests {
|
||||
assert!(cors.start(&mut req).unwrap().is_done());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "MissingOrigin")]
|
||||
fn test_validate_missing_origin() {
|
||||
let cors = Cors::build()
|
||||
.allowed_origin("https://www.example.com")
|
||||
.finish();
|
||||
|
||||
let mut req = HttpRequest::default();
|
||||
cors.start(&mut req).unwrap();
|
||||
}
|
||||
// #[test]
|
||||
// #[should_panic(expected = "MissingOrigin")]
|
||||
// fn test_validate_missing_origin() {
|
||||
// let mut cors = Cors::build()
|
||||
// .allowed_origin("https://www.example.com")
|
||||
// .finish();
|
||||
// let mut req = HttpRequest::default();
|
||||
// cors.start(&mut req).unwrap();
|
||||
// }
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "OriginNotAllowed")]
|
||||
@ -1127,10 +1134,19 @@ mod tests {
|
||||
})
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/test"))
|
||||
.header("ORIGIN", "https://www.example2.com")
|
||||
.finish()
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/test"))
|
||||
|
@ -511,7 +511,7 @@ where
|
||||
match payload.read_exact(boundary.len() + 4)? {
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
Async::Ready(None) => Err(MultipartError::Incomplete),
|
||||
Async::Ready(Some(chunk)) => {
|
||||
Async::Ready(Some(mut chunk)) => {
|
||||
if &chunk[..2] == b"\r\n"
|
||||
&& &chunk[2..4] == b"--"
|
||||
&& &chunk[4..] == boundary.as_bytes()
|
||||
@ -519,7 +519,10 @@ where
|
||||
payload.unread_data(chunk);
|
||||
Ok(Async::Ready(None))
|
||||
} else {
|
||||
Ok(Async::Ready(Some(chunk)))
|
||||
// \r might be part of data stream
|
||||
let ch = chunk.split_to(1);
|
||||
payload.unread_data(chunk);
|
||||
Ok(Async::Ready(Some(ch)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -58,6 +58,15 @@ impl<'a> Params<'a> {
|
||||
self.0.push((name, value));
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&mut self, name: &str) {
|
||||
for idx in (0..self.0.len()).rev() {
|
||||
if self.0[idx].0 == name {
|
||||
self.0.remove(idx);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if there are any matched patterns
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
|
@ -262,7 +262,7 @@ impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> {
|
||||
_s: PhantomData,
|
||||
})
|
||||
}
|
||||
Err(err) => return ProcessResponse::init(err.into()),
|
||||
Err(err) => return RunMiddlewares::init(info, err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -294,13 +294,13 @@ impl<S: 'static, H: PipelineHandler<S>> StartMiddlewares<S, H> {
|
||||
continue 'outer;
|
||||
}
|
||||
Err(err) => {
|
||||
return Some(ProcessResponse::init(err.into()))
|
||||
return Some(RunMiddlewares::init(info, err.into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => return Some(ProcessResponse::init(err.into())),
|
||||
Err(err) => return Some(RunMiddlewares::init(info, err.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
61
src/pred.rs
61
src/pred.rs
@ -192,6 +192,45 @@ impl<S: 'static> Predicate<S> for HeaderPredicate<S> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Return predicate that matches if request contains specified Host name.
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::{pred, App, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// App::new().resource("/index.html", |r| {
|
||||
/// r.route()
|
||||
/// .filter(pred::Host("www.rust-lang.org"))
|
||||
/// .f(|_| HttpResponse::MethodNotAllowed())
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn Host<S: 'static, H: AsRef<str>>(host: H) -> HostPredicate<S> {
|
||||
HostPredicate(host.as_ref().to_string(), None, PhantomData)
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct HostPredicate<S>(String, Option<String>, PhantomData<S>);
|
||||
|
||||
impl<S> HostPredicate<S> {
|
||||
/// Set reuest scheme to match
|
||||
pub fn scheme<H: AsRef<str>>(&mut self, scheme: H) {
|
||||
self.1 = Some(scheme.as_ref().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: 'static> Predicate<S> for HostPredicate<S> {
|
||||
fn check(&self, req: &mut HttpRequest<S>) -> bool {
|
||||
let info = req.connection_info();
|
||||
if let Some(ref scheme) = self.1 {
|
||||
self.0 == info.host() && scheme == info.scheme()
|
||||
} else {
|
||||
self.0 == info.host()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@ -224,6 +263,28 @@ mod tests {
|
||||
assert!(!pred.check(&mut req));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_host() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::HOST,
|
||||
header::HeaderValue::from_static("www.rust-lang.org"),
|
||||
);
|
||||
let mut req = HttpRequest::new(
|
||||
Method::GET,
|
||||
Uri::from_str("/").unwrap(),
|
||||
Version::HTTP_11,
|
||||
headers,
|
||||
None,
|
||||
);
|
||||
|
||||
let pred = Host("www.rust-lang.org");
|
||||
assert!(pred.check(&mut req));
|
||||
|
||||
let pred = Host("localhost");
|
||||
assert!(!pred.check(&mut req));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_methods() {
|
||||
let mut req = HttpRequest::new(
|
||||
|
57
src/route.rs
57
src/route.rs
@ -66,13 +66,12 @@ impl<S: 'static> Route<S> {
|
||||
/// # extern crate actix_web;
|
||||
/// # use actix_web::*;
|
||||
/// # fn main() {
|
||||
/// App::new()
|
||||
/// .resource("/path", |r|
|
||||
/// r.route()
|
||||
/// .filter(pred::Get())
|
||||
/// .filter(pred::Header("content-type", "text/plain"))
|
||||
/// .f(|req| HttpResponse::Ok())
|
||||
/// )
|
||||
/// App::new().resource("/path", |r| {
|
||||
/// r.route()
|
||||
/// .filter(pred::Get())
|
||||
/// .filter(pred::Header("content-type", "text/plain"))
|
||||
/// .f(|req| HttpResponse::Ok())
|
||||
/// })
|
||||
/// # .finish();
|
||||
/// # }
|
||||
/// ```
|
||||
@ -115,7 +114,7 @@ impl<S: 'static> Route<S> {
|
||||
/// # extern crate actix_web;
|
||||
/// # extern crate futures;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// use actix_web::{App, Path, Result, http};
|
||||
/// use actix_web::{http, App, Path, Result};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct Info {
|
||||
@ -129,8 +128,9 @@ impl<S: 'static> Route<S> {
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with(index),
|
||||
/// ); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@ -143,7 +143,7 @@ impl<S: 'static> Route<S> {
|
||||
/// # extern crate futures;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// # use std::collections::HashMap;
|
||||
/// use actix_web::{http, App, Query, Path, Result, Json};
|
||||
/// use actix_web::{http, App, Json, Path, Query, Result};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct Info {
|
||||
@ -151,14 +151,17 @@ impl<S: 'static> Route<S> {
|
||||
/// }
|
||||
///
|
||||
/// /// extract path info using serde
|
||||
/// fn index(info: (Path<Info>, Query<HashMap<String, String>>, Json<Info>)) -> Result<String> {
|
||||
/// fn index(
|
||||
/// info: (Path<Info>, Query<HashMap<String, String>>, Json<Info>),
|
||||
/// ) -> Result<String> {
|
||||
/// Ok(format!("Welcome {}!", info.0.username))
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with(index),
|
||||
/// ); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
pub fn with<T, F, R>(&mut self, handler: F) -> ExtractorConfig<S, T>
|
||||
@ -181,7 +184,7 @@ impl<S: 'static> Route<S> {
|
||||
/// # extern crate actix_web;
|
||||
/// # extern crate futures;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// use actix_web::{App, Path, Error, http};
|
||||
/// use actix_web::{http, App, Error, Path};
|
||||
/// use futures::Future;
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
@ -190,15 +193,15 @@ impl<S: 'static> Route<S> {
|
||||
/// }
|
||||
///
|
||||
/// /// extract path info using serde
|
||||
/// fn index(info: Path<Info>) -> Box<Future<Item=&'static str, Error=Error>> {
|
||||
/// fn index(info: Path<Info>) -> Box<Future<Item = &'static str, Error = Error>> {
|
||||
/// unimplemented!()
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET)
|
||||
/// .with_async(index)); // <- use `with` extractor
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with_async(index),
|
||||
/// ); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
pub fn with_async<T, F, R, I, E>(&mut self, handler: F) -> ExtractorConfig<S, T>
|
||||
@ -222,7 +225,7 @@ impl<S: 'static> Route<S> {
|
||||
/// # extern crate actix_web;
|
||||
/// # extern crate futures;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// use actix_web::{App, Query, Path, Result, http};
|
||||
/// use actix_web::{http, App, Path, Query, Result};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct PParam {
|
||||
@ -241,8 +244,9 @@ impl<S: 'static> Route<S> {
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with2(index)); // <- use `with` extractor
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with2(index),
|
||||
/// ); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
pub fn with2<T1, T2, F, R>(
|
||||
@ -424,7 +428,7 @@ impl<S: 'static> StartMiddlewares<S> {
|
||||
_s: PhantomData,
|
||||
})
|
||||
}
|
||||
Err(err) => return FinishingMiddlewares::init(info, err.into()),
|
||||
Err(err) => return RunMiddlewares::init(info, err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -455,16 +459,13 @@ impl<S: 'static> StartMiddlewares<S> {
|
||||
continue 'outer;
|
||||
}
|
||||
Err(err) => {
|
||||
return Some(FinishingMiddlewares::init(
|
||||
info,
|
||||
err.into(),
|
||||
))
|
||||
return Some(RunMiddlewares::init(info, err.into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => return Some(FinishingMiddlewares::init(info, err.into())),
|
||||
Err(err) => return Some(RunMiddlewares::init(info, err.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -311,8 +311,16 @@ impl Resource {
|
||||
None
|
||||
}
|
||||
}
|
||||
PatternType::Prefix(ref s) => if path.starts_with(s) {
|
||||
PatternType::Prefix(ref s) => if path == s {
|
||||
Some(s.len())
|
||||
} else if path.starts_with(s)
|
||||
&& (s.ends_with('/') || path.split_at(s.len()).1.starts_with('/'))
|
||||
{
|
||||
if s.ends_with('/') {
|
||||
Some(s.len() - 1)
|
||||
} else {
|
||||
Some(s.len())
|
||||
}
|
||||
} else {
|
||||
None
|
||||
},
|
||||
@ -327,22 +335,41 @@ impl Resource {
|
||||
U: IntoIterator<Item = I>,
|
||||
I: AsRef<str>,
|
||||
{
|
||||
let mut iter = elements.into_iter();
|
||||
let mut path = if self.rtp != ResourceType::External {
|
||||
format!("{}/", router.prefix())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
for el in &self.elements {
|
||||
match *el {
|
||||
PatternElement::Str(ref s) => path.push_str(s),
|
||||
PatternElement::Var(_) => {
|
||||
if let Some(val) = iter.next() {
|
||||
path.push_str(val.as_ref())
|
||||
} else {
|
||||
return Err(UrlGenerationError::NotEnoughElements);
|
||||
let mut path = match self.tp {
|
||||
PatternType::Prefix(ref p) => p.to_owned(),
|
||||
PatternType::Static(ref p) => p.to_owned(),
|
||||
PatternType::Dynamic(..) => {
|
||||
let mut path = String::new();
|
||||
let mut iter = elements.into_iter();
|
||||
for el in &self.elements {
|
||||
match *el {
|
||||
PatternElement::Str(ref s) => path.push_str(s),
|
||||
PatternElement::Var(_) => {
|
||||
if let Some(val) = iter.next() {
|
||||
path.push_str(val.as_ref())
|
||||
} else {
|
||||
return Err(UrlGenerationError::NotEnoughElements);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
};
|
||||
|
||||
if self.rtp != ResourceType::External {
|
||||
let prefix = router.prefix();
|
||||
if prefix.ends_with('/') {
|
||||
if path.starts_with('/') {
|
||||
path.insert_str(0, &prefix[..prefix.len() - 1]);
|
||||
} else {
|
||||
path.insert_str(0, prefix);
|
||||
}
|
||||
} else {
|
||||
if !path.starts_with('/') {
|
||||
path.insert(0, '/');
|
||||
}
|
||||
path.insert_str(0, prefix);
|
||||
}
|
||||
}
|
||||
Ok(path)
|
||||
@ -407,6 +434,10 @@ impl Resource {
|
||||
}
|
||||
}
|
||||
|
||||
if !el.is_empty() {
|
||||
elems.push(PatternElement::Str(el.clone()));
|
||||
}
|
||||
|
||||
let re = if is_dynamic {
|
||||
if !for_prefix {
|
||||
re1.push('$');
|
||||
@ -439,7 +470,7 @@ mod tests {
|
||||
use test::TestRequest;
|
||||
|
||||
#[test]
|
||||
fn test_recognizer() {
|
||||
fn test_recognizer10() {
|
||||
let routes = vec![
|
||||
(Resource::new("", "/name"), Some(ResourceHandler::default())),
|
||||
(
|
||||
@ -462,6 +493,10 @@ mod tests {
|
||||
Resource::new("", "/v/{tail:.*}"),
|
||||
Some(ResourceHandler::default()),
|
||||
),
|
||||
(
|
||||
Resource::new("", "/test2/{test}.html"),
|
||||
Some(ResourceHandler::default()),
|
||||
),
|
||||
(
|
||||
Resource::new("", "{test}/index.html"),
|
||||
Some(ResourceHandler::default()),
|
||||
@ -499,8 +534,12 @@ mod tests {
|
||||
"blah-blah/index.html"
|
||||
);
|
||||
|
||||
let mut req = TestRequest::with_uri("/bbb/index.html").finish();
|
||||
let mut req = TestRequest::with_uri("/test2/index.html").finish();
|
||||
assert_eq!(rec.recognize(&mut req), Some(6));
|
||||
assert_eq!(req.match_info().get("test").unwrap(), "index");
|
||||
|
||||
let mut req = TestRequest::with_uri("/bbb/index.html").finish();
|
||||
assert_eq!(rec.recognize(&mut req), Some(7));
|
||||
assert_eq!(req.match_info().get("test").unwrap(), "bbb");
|
||||
}
|
||||
|
||||
|
268
src/scope.rs
268
src/scope.rs
@ -38,12 +38,12 @@ type NestedInfo<S> = (Resource, Route<S>, Vec<Box<Predicate<S>>>);
|
||||
/// use actix_web::{http, App, HttpRequest, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .scope("/{project_id}/", |scope| {
|
||||
/// scope.resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path2", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed()))
|
||||
/// });
|
||||
/// let app = App::new().scope("/{project_id}/", |scope| {
|
||||
/// scope
|
||||
/// .resource("/path1", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path2", |r| r.f(|_| HttpResponse::Ok()))
|
||||
/// .resource("/path3", |r| r.f(|_| HttpResponse::MethodNotAllowed()))
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@ -89,13 +89,14 @@ impl<S: 'static> Scope<S> {
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .scope("/app", |scope| {
|
||||
/// scope.filter(pred::Header("content-type", "text/plain"))
|
||||
/// .route("/test1", http::Method::GET, index)
|
||||
/// .route("/test2", http::Method::POST,
|
||||
/// |_: HttpRequest| HttpResponse::MethodNotAllowed())
|
||||
/// });
|
||||
/// let app = App::new().scope("/app", |scope| {
|
||||
/// scope
|
||||
/// .filter(pred::Header("content-type", "text/plain"))
|
||||
/// .route("/test1", http::Method::GET, index)
|
||||
/// .route("/test2", http::Method::POST, |_: HttpRequest| {
|
||||
/// HttpResponse::MethodNotAllowed()
|
||||
/// })
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn filter<T: Predicate<S> + 'static>(mut self, p: T) -> Self {
|
||||
@ -116,12 +117,11 @@ impl<S: 'static> Scope<S> {
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .scope("/app", |scope| {
|
||||
/// scope.with_state("/state2", AppState, |scope| {
|
||||
/// scope.resource("/test1", |r| r.f(index))
|
||||
/// })
|
||||
/// });
|
||||
/// let app = App::new().scope("/app", |scope| {
|
||||
/// scope.with_state("/state2", AppState, |scope| {
|
||||
/// scope.resource("/test1", |r| r.f(index))
|
||||
/// })
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn with_state<F, T: 'static>(mut self, path: &str, state: T, f: F) -> Scope<S>
|
||||
@ -137,14 +137,6 @@ impl<S: 'static> Scope<S> {
|
||||
};
|
||||
let mut scope = f(scope);
|
||||
|
||||
let mut path = path.trim().trim_right_matches('/').to_owned();
|
||||
if !path.is_empty() && !path.starts_with('/') {
|
||||
path.insert(0, '/')
|
||||
}
|
||||
if !path.ends_with('/') {
|
||||
path.push('/');
|
||||
}
|
||||
|
||||
let state = Rc::new(state);
|
||||
let filters: Vec<Box<Predicate<S>>> = vec![Box::new(FiltersWrapper {
|
||||
state: Rc::clone(&state),
|
||||
@ -170,12 +162,9 @@ impl<S: 'static> Scope<S> {
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::with_state(AppState)
|
||||
/// .scope("/app", |scope| {
|
||||
/// scope.nested("/v1", |scope| {
|
||||
/// scope.resource("/test1", |r| r.f(index))
|
||||
/// })
|
||||
/// });
|
||||
/// let app = App::with_state(AppState).scope("/app", |scope| {
|
||||
/// scope.nested("/v1", |scope| scope.resource("/test1", |r| r.f(index)))
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn nested<F>(mut self, path: &str, f: F) -> Scope<S>
|
||||
@ -191,14 +180,6 @@ impl<S: 'static> Scope<S> {
|
||||
};
|
||||
let mut scope = f(scope);
|
||||
|
||||
let mut path = path.trim().trim_right_matches('/').to_owned();
|
||||
if !path.is_empty() && !path.starts_with('/') {
|
||||
path.insert(0, '/')
|
||||
}
|
||||
if !path.ends_with('/') {
|
||||
path.push('/');
|
||||
}
|
||||
|
||||
let filters = scope.take_filters();
|
||||
self.nested.push((
|
||||
Resource::prefix("", &path),
|
||||
@ -227,12 +208,13 @@ impl<S: 'static> Scope<S> {
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .scope("/app", |scope| {
|
||||
/// scope.route("/test1", http::Method::GET, index)
|
||||
/// .route("/test2", http::Method::POST,
|
||||
/// |_: HttpRequest| HttpResponse::MethodNotAllowed())
|
||||
/// });
|
||||
/// let app = App::new().scope("/app", |scope| {
|
||||
/// scope.route("/test1", http::Method::GET, index).route(
|
||||
/// "/test2",
|
||||
/// http::Method::POST,
|
||||
/// |_: HttpRequest| HttpResponse::MethodNotAllowed(),
|
||||
/// )
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn route<T, F, R>(mut self, path: &str, method: Method, f: F) -> Scope<S>
|
||||
@ -253,7 +235,12 @@ impl<S: 'static> Scope<S> {
|
||||
|
||||
let mut handler = ResourceHandler::default();
|
||||
handler.method(method).with(f);
|
||||
let pattern = Resource::new(handler.get_name(), path);
|
||||
let pattern = Resource::with_prefix(
|
||||
handler.get_name(),
|
||||
path,
|
||||
if path.is_empty() { "" } else { "/" },
|
||||
false,
|
||||
);
|
||||
Rc::get_mut(&mut self.resources)
|
||||
.expect("Can not use after configuration")
|
||||
.push((pattern, Rc::new(UnsafeCell::new(handler))));
|
||||
@ -272,17 +259,16 @@ impl<S: 'static> Scope<S> {
|
||||
/// use actix_web::*;
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new()
|
||||
/// .scope("/api", |scope| {
|
||||
/// scope.resource("/users/{userid}/{friend}", |r| {
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// r.route()
|
||||
/// .filter(pred::Any(pred::Get()).or(pred::Put()))
|
||||
/// .filter(pred::Header("Content-Type", "text/plain"))
|
||||
/// .f(|_| HttpResponse::Ok())
|
||||
/// })
|
||||
/// });
|
||||
/// let app = App::new().scope("/api", |scope| {
|
||||
/// scope.resource("/users/{userid}/{friend}", |r| {
|
||||
/// r.get().f(|_| HttpResponse::Ok());
|
||||
/// r.head().f(|_| HttpResponse::MethodNotAllowed());
|
||||
/// r.route()
|
||||
/// .filter(pred::Any(pred::Get()).or(pred::Put()))
|
||||
/// .filter(pred::Header("Content-Type", "text/plain"))
|
||||
/// .f(|_| HttpResponse::Ok())
|
||||
/// })
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub fn resource<F, R>(mut self, path: &str, f: F) -> Scope<S>
|
||||
@ -293,7 +279,12 @@ impl<S: 'static> Scope<S> {
|
||||
let mut handler = ResourceHandler::default();
|
||||
f(&mut handler);
|
||||
|
||||
let pattern = Resource::new(handler.get_name(), path);
|
||||
let pattern = Resource::with_prefix(
|
||||
handler.get_name(),
|
||||
path,
|
||||
if path.is_empty() { "" } else { "/" },
|
||||
false,
|
||||
);
|
||||
Rc::get_mut(&mut self.resources)
|
||||
.expect("Can not use after configuration")
|
||||
.push((pattern, Rc::new(UnsafeCell::new(handler))));
|
||||
@ -329,13 +320,13 @@ impl<S: 'static> Scope<S> {
|
||||
impl<S: 'static> RouteHandler<S> for Scope<S> {
|
||||
fn handle(&mut self, mut req: HttpRequest<S>) -> AsyncResult<HttpResponse> {
|
||||
let path = unsafe { &*(&req.match_info()["tail"] as *const _) };
|
||||
let path = if path == "" { "/" } else { path };
|
||||
|
||||
// recognize resources
|
||||
for &(ref pattern, ref resource) in self.resources.iter() {
|
||||
if pattern.match_with_params(path, req.match_info_mut()) {
|
||||
let default = unsafe { &mut *self.default.as_ref().get() };
|
||||
|
||||
req.match_info_mut().remove("tail");
|
||||
if self.middlewares.is_empty() {
|
||||
let resource = unsafe { &mut *resource.get() };
|
||||
return resource.handle(req, Some(default));
|
||||
@ -363,16 +354,12 @@ impl<S: 'static> RouteHandler<S> for Scope<S> {
|
||||
continue 'outer;
|
||||
}
|
||||
}
|
||||
let prefix_len = len + prefix_len - 1;
|
||||
let prefix_len = len + prefix_len;
|
||||
let path: &'static str =
|
||||
unsafe { &*(&req.path()[prefix_len..] as *const _) };
|
||||
|
||||
req.set_prefix_len(prefix_len as u16);
|
||||
if path.is_empty() {
|
||||
req.match_info_mut().set("tail", "/");
|
||||
} else {
|
||||
req.match_info_mut().set("tail", path);
|
||||
}
|
||||
req.match_info_mut().set("tail", path);
|
||||
|
||||
let hnd: &mut RouteHandler<_> =
|
||||
unsafe { (&mut *(handler.get())).as_mut() };
|
||||
@ -528,7 +515,7 @@ impl<S: 'static> StartMiddlewares<S> {
|
||||
_s: PhantomData,
|
||||
})
|
||||
}
|
||||
Err(err) => return Response::init(err.into()),
|
||||
Err(err) => return RunMiddlewares::init(info, err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -564,12 +551,14 @@ impl<S: 'static> StartMiddlewares<S> {
|
||||
self.fut = Some(fut);
|
||||
continue 'outer;
|
||||
}
|
||||
Err(err) => return Some(Response::init(err.into())),
|
||||
Err(err) => {
|
||||
return Some(RunMiddlewares::init(info, err.into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => return Some(Response::init(err.into())),
|
||||
Err(err) => return Some(RunMiddlewares::init(info, err.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -783,6 +772,59 @@ mod tests {
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_root() {
|
||||
let mut app = App::new()
|
||||
.scope("/app", |scope| {
|
||||
scope
|
||||
.resource("", |r| r.f(|_| HttpResponse::Ok()))
|
||||
.resource("/", |r| r.f(|_| HttpResponse::Created()))
|
||||
})
|
||||
.finish();
|
||||
|
||||
let req = TestRequest::with_uri("/app").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/app/").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_root2() {
|
||||
let mut app = App::new()
|
||||
.scope("/app/", |scope| {
|
||||
scope.resource("", |r| r.f(|_| HttpResponse::Ok()))
|
||||
})
|
||||
.finish();
|
||||
|
||||
let req = TestRequest::with_uri("/app").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let req = TestRequest::with_uri("/app/").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_root3() {
|
||||
let mut app = App::new()
|
||||
.scope("/app/", |scope| {
|
||||
scope.resource("/", |r| r.f(|_| HttpResponse::Ok()))
|
||||
})
|
||||
.finish();
|
||||
|
||||
let req = TestRequest::with_uri("/app").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let req = TestRequest::with_uri("/app/").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_route() {
|
||||
let mut app = App::new()
|
||||
@ -884,6 +926,71 @@ mod tests {
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_with_state_root() {
|
||||
struct State;
|
||||
|
||||
let mut app = App::new()
|
||||
.scope("/app", |scope| {
|
||||
scope.with_state("/t1", State, |scope| {
|
||||
scope
|
||||
.resource("", |r| r.f(|_| HttpResponse::Ok()))
|
||||
.resource("/", |r| r.f(|_| HttpResponse::Created()))
|
||||
})
|
||||
})
|
||||
.finish();
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1/").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_with_state_root2() {
|
||||
struct State;
|
||||
|
||||
let mut app = App::new()
|
||||
.scope("/app", |scope| {
|
||||
scope.with_state("/t1/", State, |scope| {
|
||||
scope.resource("", |r| r.f(|_| HttpResponse::Ok()))
|
||||
})
|
||||
})
|
||||
.finish();
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1/").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_with_state_root3() {
|
||||
struct State;
|
||||
|
||||
let mut app = App::new()
|
||||
.scope("/app", |scope| {
|
||||
scope.with_state("/t1/", State, |scope| {
|
||||
scope.resource("/", |r| r.f(|_| HttpResponse::Ok()))
|
||||
})
|
||||
})
|
||||
.finish();
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1/").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_with_state_filter() {
|
||||
struct State;
|
||||
@ -926,6 +1033,27 @@ mod tests {
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_scope_root() {
|
||||
let mut app = App::new()
|
||||
.scope("/app", |scope| {
|
||||
scope.nested("/t1", |scope| {
|
||||
scope
|
||||
.resource("", |r| r.f(|_| HttpResponse::Ok()))
|
||||
.resource("/", |r| r.f(|_| HttpResponse::Created()))
|
||||
})
|
||||
})
|
||||
.finish();
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::OK);
|
||||
|
||||
let req = TestRequest::with_uri("/app/t1/").finish();
|
||||
let resp = app.run(req);
|
||||
assert_eq!(resp.as_msg().status(), StatusCode::CREATED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_scope_filter() {
|
||||
let mut app = App::new()
|
||||
|
@ -505,6 +505,11 @@ impl ContentEncoder {
|
||||
}
|
||||
TransferEncoding::eof(buf)
|
||||
} else {
|
||||
if !(encoding == ContentEncoding::Identity
|
||||
|| encoding == ContentEncoding::Auto)
|
||||
{
|
||||
resp.headers_mut().remove(CONTENT_LENGTH);
|
||||
}
|
||||
ContentEncoder::streaming_encoding(buf, version, resp)
|
||||
}
|
||||
}
|
||||
|
@ -270,7 +270,12 @@ where
|
||||
debug!("Error sending data: {}", err);
|
||||
return Err(());
|
||||
}
|
||||
_ => (),
|
||||
Ok(Async::Ready(_)) => {
|
||||
// non consumed payload in that case close connection
|
||||
if self.payload.is_some() && self.tasks.is_empty() {
|
||||
return Ok(Async::Ready(false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#![cfg_attr(feature = "cargo-clippy", allow(redundant_field_names))]
|
||||
|
||||
use bytes::BufMut;
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use futures::{Async, Poll};
|
||||
use std::io;
|
||||
use std::rc::Rc;
|
||||
@ -45,7 +45,7 @@ impl<T: AsyncWrite, H: 'static> H1Writer<T, H> {
|
||||
stream: T, buf: SharedBytes, settings: Rc<WorkerSettings<H>>,
|
||||
) -> H1Writer<T, H> {
|
||||
H1Writer {
|
||||
flags: Flags::empty(),
|
||||
flags: Flags::KEEPALIVE,
|
||||
encoder: ContentEncoder::empty(buf.clone()),
|
||||
written: 0,
|
||||
headers_size: 0,
|
||||
@ -62,7 +62,7 @@ impl<T: AsyncWrite, H: 'static> H1Writer<T, H> {
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.written = 0;
|
||||
self.flags = Flags::empty();
|
||||
self.flags = Flags::KEEPALIVE;
|
||||
}
|
||||
|
||||
pub fn disconnected(&mut self) {
|
||||
@ -100,6 +100,16 @@ impl<T: AsyncWrite, H: 'static> Writer for H1Writer<T, H> {
|
||||
self.written
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_date(&self, dst: &mut BytesMut) {
|
||||
self.settings.set_date(dst)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn buffer(&self) -> &mut BytesMut {
|
||||
self.buffer.get_mut()
|
||||
}
|
||||
|
||||
fn start(
|
||||
&mut self, req: &mut HttpInnerMessage, msg: &mut HttpResponse,
|
||||
encoding: ContentEncoding,
|
||||
@ -108,9 +118,9 @@ impl<T: AsyncWrite, H: 'static> Writer for H1Writer<T, H> {
|
||||
self.encoder =
|
||||
ContentEncoder::for_server(self.buffer.clone(), req, msg, encoding);
|
||||
if msg.keep_alive().unwrap_or_else(|| req.keep_alive()) {
|
||||
self.flags.insert(Flags::STARTED | Flags::KEEPALIVE);
|
||||
self.flags = Flags::STARTED | Flags::KEEPALIVE;
|
||||
} else {
|
||||
self.flags.insert(Flags::STARTED);
|
||||
self.flags = Flags::STARTED;
|
||||
}
|
||||
|
||||
// Connection upgrade
|
||||
|
@ -67,7 +67,7 @@ where
|
||||
flags: Flags::empty(),
|
||||
tasks: VecDeque::new(),
|
||||
state: State::Handshake(server::handshake(IoWrapper {
|
||||
unread: Some(buf),
|
||||
unread: if buf.is_empty() { None } else { Some(buf) },
|
||||
inner: io,
|
||||
})),
|
||||
keepalive_timer: None,
|
||||
|
@ -71,6 +71,16 @@ impl<H: 'static> Writer for H2Writer<H> {
|
||||
self.written
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_date(&self, dst: &mut BytesMut) {
|
||||
self.settings.set_date(dst)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn buffer(&self) -> &mut BytesMut {
|
||||
self.buffer.get_mut()
|
||||
}
|
||||
|
||||
fn start(
|
||||
&mut self, req: &mut HttpInnerMessage, msg: &mut HttpResponse,
|
||||
encoding: ContentEncoding,
|
||||
@ -79,9 +89,6 @@ impl<H: 'static> Writer for H2Writer<H> {
|
||||
self.flags.insert(Flags::STARTED);
|
||||
self.encoder =
|
||||
ContentEncoder::for_server(self.buffer.clone(), req, msg, encoding);
|
||||
if let Body::Empty = *msg.body() {
|
||||
self.flags.insert(Flags::EOF);
|
||||
}
|
||||
|
||||
// http2 specific
|
||||
msg.headers_mut().remove(CONNECTION);
|
||||
@ -98,15 +105,22 @@ impl<H: 'static> Writer for H2Writer<H> {
|
||||
let body = msg.replace_body(Body::Empty);
|
||||
match body {
|
||||
Body::Binary(ref bytes) => {
|
||||
let mut val = BytesMut::new();
|
||||
helpers::convert_usize(bytes.len(), &mut val);
|
||||
let l = val.len();
|
||||
msg.headers_mut().insert(
|
||||
CONTENT_LENGTH,
|
||||
HeaderValue::try_from(val.split_to(l - 2).freeze()).unwrap(),
|
||||
);
|
||||
if bytes.is_empty() {
|
||||
msg.headers_mut()
|
||||
.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));
|
||||
self.flags.insert(Flags::EOF);
|
||||
} else {
|
||||
let mut val = BytesMut::new();
|
||||
helpers::convert_usize(bytes.len(), &mut val);
|
||||
let l = val.len();
|
||||
msg.headers_mut().insert(
|
||||
CONTENT_LENGTH,
|
||||
HeaderValue::try_from(val.split_to(l - 2).freeze()).unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Body::Empty => {
|
||||
self.flags.insert(Flags::EOF);
|
||||
msg.headers_mut()
|
||||
.insert(CONTENT_LENGTH, HeaderValue::from_static("0"));
|
||||
}
|
||||
@ -131,14 +145,18 @@ impl<H: 'static> Writer for H2Writer<H> {
|
||||
trace!("Response: {:?}", msg);
|
||||
|
||||
if let Body::Binary(bytes) = body {
|
||||
self.flags.insert(Flags::EOF);
|
||||
self.written = bytes.len() as u64;
|
||||
self.encoder.write(bytes)?;
|
||||
if let Some(ref mut stream) = self.stream {
|
||||
self.flags.insert(Flags::RESERVED);
|
||||
stream.reserve_capacity(cmp::min(self.buffer.len(), CHUNK_SIZE));
|
||||
if bytes.is_empty() {
|
||||
Ok(WriterState::Done)
|
||||
} else {
|
||||
self.flags.insert(Flags::EOF);
|
||||
self.written = bytes.len() as u64;
|
||||
self.encoder.write(bytes)?;
|
||||
if let Some(ref mut stream) = self.stream {
|
||||
self.flags.insert(Flags::RESERVED);
|
||||
stream.reserve_capacity(cmp::min(self.buffer.len(), CHUNK_SIZE));
|
||||
}
|
||||
Ok(WriterState::Pause)
|
||||
}
|
||||
Ok(WriterState::Pause)
|
||||
} else {
|
||||
msg.replace_body(body);
|
||||
self.buffer_capacity = msg.write_buffer_capacity();
|
||||
@ -167,10 +185,8 @@ impl<H: 'static> Writer for H2Writer<H> {
|
||||
}
|
||||
|
||||
fn write_eof(&mut self) -> io::Result<WriterState> {
|
||||
self.encoder.write_eof()?;
|
||||
|
||||
self.flags.insert(Flags::EOF);
|
||||
if !self.encoder.is_eof() {
|
||||
if !self.encoder.write_eof()? {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
"Last payload item, but eof is not reached",
|
||||
|
@ -143,7 +143,7 @@ pub(crate) fn write_status_line(version: Version, mut n: u16, bytes: &mut BytesM
|
||||
}
|
||||
|
||||
/// NOTE: bytes object has to contain enough space
|
||||
pub(crate) fn write_content_length(mut n: usize, bytes: &mut BytesMut) {
|
||||
pub fn write_content_length(mut n: usize, bytes: &mut BytesMut) {
|
||||
if n < 10 {
|
||||
let mut buf: [u8; 21] = [
|
||||
b'\r', b'\n', b'c', b'o', b'n', b't', b'e', b'n', b't', b'-', b'l', b'e',
|
||||
|
@ -3,7 +3,8 @@ use std::net::Shutdown;
|
||||
use std::{io, time};
|
||||
|
||||
use actix;
|
||||
use futures::Poll;
|
||||
use bytes::BytesMut;
|
||||
use futures::{Async, Poll};
|
||||
use tokio_core::net::TcpStream;
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
|
||||
@ -24,6 +25,9 @@ mod worker;
|
||||
pub use self::settings::ServerSettings;
|
||||
pub use self::srv::HttpServer;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::helpers::write_content_length;
|
||||
|
||||
use body::Binary;
|
||||
use error::Error;
|
||||
use header::ContentEncoding;
|
||||
@ -132,13 +136,15 @@ impl HttpHandler for Box<HttpHandler> {
|
||||
#[doc(hidden)]
|
||||
pub trait HttpHandlerTask {
|
||||
/// Poll task, this method is used before or after *io* object is available
|
||||
fn poll(&mut self) -> Poll<(), Error>;
|
||||
fn poll(&mut self) -> Poll<(), Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
/// Poll task when *io* object is available
|
||||
fn poll_io(&mut self, io: &mut Writer) -> Poll<bool, Error>;
|
||||
|
||||
/// Connection is disconnected
|
||||
fn disconnected(&mut self);
|
||||
fn disconnected(&mut self) {}
|
||||
}
|
||||
|
||||
/// Conversion helper trait
|
||||
@ -168,8 +174,16 @@ pub enum WriterState {
|
||||
#[doc(hidden)]
|
||||
/// Stream writer
|
||||
pub trait Writer {
|
||||
/// number of bytes written to the stream
|
||||
fn written(&self) -> u64;
|
||||
|
||||
#[doc(hidden)]
|
||||
fn set_date(&self, st: &mut BytesMut);
|
||||
|
||||
#[doc(hidden)]
|
||||
#[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref))]
|
||||
fn buffer(&self) -> &mut BytesMut;
|
||||
|
||||
fn start(
|
||||
&mut self, req: &mut HttpInnerMessage, resp: &mut HttpResponse,
|
||||
encoding: ContentEncoding,
|
||||
|
@ -309,7 +309,7 @@ where
|
||||
|
||||
/// The socket address to bind
|
||||
///
|
||||
/// To mind multiple addresses this method can be call multiple times.
|
||||
/// To bind multiple addresses this method can be called multiple times.
|
||||
pub fn bind<S: net::ToSocketAddrs>(mut self, addr: S) -> io::Result<Self> {
|
||||
let sockets = self.bind2(addr)?;
|
||||
self.sockets.extend(sockets);
|
||||
@ -319,7 +319,7 @@ where
|
||||
#[cfg(feature = "tls")]
|
||||
/// The ssl socket address to bind
|
||||
///
|
||||
/// To mind multiple addresses this method can be call multiple times.
|
||||
/// To bind multiple addresses this method can be called multiple times.
|
||||
pub fn bind_tls<S: net::ToSocketAddrs>(
|
||||
mut self, addr: S, acceptor: TlsAcceptor,
|
||||
) -> io::Result<Self> {
|
||||
@ -450,7 +450,6 @@ impl<H: IntoHttpHandler> HttpServer<H> {
|
||||
self.accept.push(start_accept_thread(
|
||||
token,
|
||||
sock,
|
||||
self.backlog,
|
||||
tx.clone(),
|
||||
socks.clone(),
|
||||
workers.clone(),
|
||||
@ -782,7 +781,7 @@ enum Command {
|
||||
}
|
||||
|
||||
fn start_accept_thread(
|
||||
token: usize, sock: Socket, backlog: i32, srv: mpsc::UnboundedSender<ServerCommand>,
|
||||
token: usize, sock: Socket, srv: mpsc::UnboundedSender<ServerCommand>,
|
||||
socks: Slab<SocketInfo>,
|
||||
mut workers: Vec<(usize, mpsc::UnboundedSender<Conn<net::TcpStream>>)>,
|
||||
) -> (mio::SetReadiness, sync_mpsc::Sender<Command>) {
|
||||
@ -892,8 +891,8 @@ fn start_accept_thread(
|
||||
},
|
||||
CMD => match rx.try_recv() {
|
||||
Ok(cmd) => match cmd {
|
||||
Command::Pause => if let Some(server) = server.take() {
|
||||
if let Err(err) = poll.deregister(&server) {
|
||||
Command::Pause => if let Some(ref server) = server {
|
||||
if let Err(err) = poll.deregister(server) {
|
||||
error!(
|
||||
"Can not deregister server socket {}",
|
||||
err
|
||||
@ -906,15 +905,6 @@ fn start_accept_thread(
|
||||
}
|
||||
},
|
||||
Command::Resume => {
|
||||
let lst = create_tcp_listener(addr, backlog)
|
||||
.expect("Can not create net::TcpListener");
|
||||
|
||||
server = Some(
|
||||
mio::net::TcpListener::from_std(lst).expect(
|
||||
"Can not create mio::net::TcpListener",
|
||||
),
|
||||
);
|
||||
|
||||
if let Some(ref server) = server {
|
||||
if let Err(err) = poll.register(
|
||||
server,
|
||||
|
@ -239,9 +239,9 @@ impl StreamHandlerType {
|
||||
match *self {
|
||||
StreamHandlerType::Normal => "http",
|
||||
#[cfg(feature = "tls")]
|
||||
StreamHandlerType::Tls(ref acceptor) => "https",
|
||||
StreamHandlerType::Tls(_) => "https",
|
||||
#[cfg(feature = "alpn")]
|
||||
StreamHandlerType::Alpn(ref acceptor) => "https",
|
||||
StreamHandlerType::Alpn(_) => "https",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -217,7 +217,7 @@ impl TestServer {
|
||||
|
||||
/// Create `POST` request
|
||||
pub fn post(&self) -> ClientRequestBuilder {
|
||||
ClientRequest::get(self.url("/").as_str())
|
||||
ClientRequest::post(self.url("/").as_str())
|
||||
}
|
||||
|
||||
/// Create `HEAD` request
|
||||
|
@ -113,6 +113,7 @@ pub struct Client {
|
||||
protocols: Option<String>,
|
||||
conn: Addr<Unsync, ClientConnector>,
|
||||
max_size: usize,
|
||||
no_masking: bool,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@ -132,6 +133,7 @@ impl Client {
|
||||
origin: None,
|
||||
protocols: None,
|
||||
max_size: 65_536,
|
||||
no_masking: false,
|
||||
conn,
|
||||
};
|
||||
cl.request.uri(uri.as_ref());
|
||||
@ -186,6 +188,12 @@ impl Client {
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable payload masking. By default ws client masks frame payload.
|
||||
pub fn no_masking(mut self) -> Self {
|
||||
self.no_masking = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set request header
|
||||
pub fn header<K, V>(mut self, key: K, value: V) -> Self
|
||||
where
|
||||
@ -248,7 +256,7 @@ impl Client {
|
||||
}
|
||||
|
||||
// start handshake
|
||||
ClientHandshake::new(request, self.max_size)
|
||||
ClientHandshake::new(request, self.max_size, self.no_masking)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -269,10 +277,13 @@ pub struct ClientHandshake {
|
||||
key: String,
|
||||
error: Option<ClientError>,
|
||||
max_size: usize,
|
||||
no_masking: bool,
|
||||
}
|
||||
|
||||
impl ClientHandshake {
|
||||
fn new(mut request: ClientRequest, max_size: usize) -> ClientHandshake {
|
||||
fn new(
|
||||
mut request: ClientRequest, max_size: usize, no_masking: bool,
|
||||
) -> ClientHandshake {
|
||||
// Generate a random key for the `Sec-WebSocket-Key` header.
|
||||
// a base64-encoded (see Section 4 of [RFC4648]) value that,
|
||||
// when decoded, is 16 bytes in length (RFC 6455)
|
||||
@ -292,6 +303,7 @@ impl ClientHandshake {
|
||||
ClientHandshake {
|
||||
key,
|
||||
max_size,
|
||||
no_masking,
|
||||
request: Some(request.send()),
|
||||
tx: Some(tx),
|
||||
error: None,
|
||||
@ -305,6 +317,7 @@ impl ClientHandshake {
|
||||
tx: None,
|
||||
error: Some(err),
|
||||
max_size: 0,
|
||||
no_masking: false,
|
||||
}
|
||||
}
|
||||
|
||||
@ -415,6 +428,7 @@ impl Future for ClientHandshake {
|
||||
ClientReader {
|
||||
inner: Rc::clone(&inner),
|
||||
max_size: self.max_size,
|
||||
no_masking: self.no_masking,
|
||||
},
|
||||
ClientWriter { inner },
|
||||
)))
|
||||
@ -424,6 +438,7 @@ impl Future for ClientHandshake {
|
||||
pub struct ClientReader {
|
||||
inner: Rc<UnsafeCell<Inner>>,
|
||||
max_size: usize,
|
||||
no_masking: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ClientReader {
|
||||
@ -445,13 +460,14 @@ impl Stream for ClientReader {
|
||||
|
||||
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
||||
let max_size = self.max_size;
|
||||
let no_masking = self.no_masking;
|
||||
let inner = self.as_mut();
|
||||
if inner.closed {
|
||||
return Ok(Async::Ready(None));
|
||||
}
|
||||
|
||||
// read
|
||||
match Frame::parse(&mut inner.rx, false, max_size) {
|
||||
match Frame::parse(&mut inner.rx, no_masking, max_size) {
|
||||
Ok(Async::Ready(Some(frame))) => {
|
||||
let (_finished, opcode, payload) = frame.unpack();
|
||||
|
||||
|
@ -368,6 +368,77 @@ fn test_path_and_query_extractor2_async4() {
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_and_path_extractor() {
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
App::new().scope("/sc", |scope| {
|
||||
scope.resource("/{num}/index.html", |r| {
|
||||
r.route()
|
||||
.with(|p: Path<(usize,)>| format!("Welcome {}!", p.0))
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
// client request
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/sc/10/index.html"))
|
||||
.finish()
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.execute(response.body()).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"Welcome 10!"));
|
||||
|
||||
// client request
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/sc/test1/index.html"))
|
||||
.finish()
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nested_scope_and_path_extractor() {
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
App::new().scope("/sc", |scope| {
|
||||
scope.nested("/{num}", |scope| {
|
||||
scope.resource("/{num}/index.html", |r| {
|
||||
r.route().with(|p: Path<(usize, usize)>| {
|
||||
format!("Welcome {} {}!", p.0, p.1)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
// client request
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/sc/10/12/index.html"))
|
||||
.finish()
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.execute(response.body()).unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(b"Welcome 10 12!"));
|
||||
|
||||
// client request
|
||||
let request = srv
|
||||
.get()
|
||||
.uri(srv.url("/sc/10/test1/index.html"))
|
||||
.finish()
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[cfg(actix_impl_trait)]
|
||||
fn test_impl_trait(
|
||||
data: (Json<Value>, Path<PParam>, Query<PParam>),
|
||||
|
@ -9,6 +9,7 @@ use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use actix::*;
|
||||
use actix_web::error::{Error, ErrorInternalServerError};
|
||||
use actix_web::*;
|
||||
use futures::{future, Future};
|
||||
use tokio_core::reactor::Timeout;
|
||||
@ -792,3 +793,207 @@ fn test_async_sync_resource_middleware_multiple() {
|
||||
thread::sleep(Duration::from_millis(40));
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
struct MiddlewareWithErr;
|
||||
|
||||
impl<S> middleware::Middleware<S> for MiddlewareWithErr {
|
||||
fn start(&self, _req: &mut HttpRequest<S>) -> Result<middleware::Started, Error> {
|
||||
Err(ErrorInternalServerError("middleware error"))
|
||||
}
|
||||
}
|
||||
|
||||
struct MiddlewareAsyncWithErr;
|
||||
|
||||
impl<S> middleware::Middleware<S> for MiddlewareAsyncWithErr {
|
||||
fn start(&self, _req: &mut HttpRequest<S>) -> Result<middleware::Started, Error> {
|
||||
Ok(middleware::Started::Future(Box::new(future::err(
|
||||
ErrorInternalServerError("middleware error"),
|
||||
))))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_middleware_chain_with_error() {
|
||||
let num1 = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = Arc::new(AtomicUsize::new(0));
|
||||
let num3 = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let act_num1 = Arc::clone(&num1);
|
||||
let act_num2 = Arc::clone(&num2);
|
||||
let act_num3 = Arc::clone(&num3);
|
||||
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
let mw1 = MiddlewareTest {
|
||||
start: Arc::clone(&act_num1),
|
||||
response: Arc::clone(&act_num2),
|
||||
finish: Arc::clone(&act_num3),
|
||||
};
|
||||
App::new()
|
||||
.middleware(mw1)
|
||||
.middleware(MiddlewareWithErr)
|
||||
.resource("/test", |r| r.h(|_| HttpResponse::Ok()))
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_middleware_async_chain_with_error() {
|
||||
let num1 = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = Arc::new(AtomicUsize::new(0));
|
||||
let num3 = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let act_num1 = Arc::clone(&num1);
|
||||
let act_num2 = Arc::clone(&num2);
|
||||
let act_num3 = Arc::clone(&num3);
|
||||
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
let mw1 = MiddlewareTest {
|
||||
start: Arc::clone(&act_num1),
|
||||
response: Arc::clone(&act_num2),
|
||||
finish: Arc::clone(&act_num3),
|
||||
};
|
||||
App::new()
|
||||
.middleware(mw1)
|
||||
.middleware(MiddlewareAsyncWithErr)
|
||||
.resource("/test", |r| r.h(|_| HttpResponse::Ok()))
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_middleware_chain_with_error() {
|
||||
let num1 = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = Arc::new(AtomicUsize::new(0));
|
||||
let num3 = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let act_num1 = Arc::clone(&num1);
|
||||
let act_num2 = Arc::clone(&num2);
|
||||
let act_num3 = Arc::clone(&num3);
|
||||
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
let mw1 = MiddlewareTest {
|
||||
start: Arc::clone(&act_num1),
|
||||
response: Arc::clone(&act_num2),
|
||||
finish: Arc::clone(&act_num3),
|
||||
};
|
||||
App::new().scope("/scope", |scope| {
|
||||
scope
|
||||
.middleware(mw1)
|
||||
.middleware(MiddlewareWithErr)
|
||||
.resource("/test", |r| r.h(|_| HttpResponse::Ok()))
|
||||
})
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/scope/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_middleware_async_chain_with_error() {
|
||||
let num1 = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = Arc::new(AtomicUsize::new(0));
|
||||
let num3 = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let act_num1 = Arc::clone(&num1);
|
||||
let act_num2 = Arc::clone(&num2);
|
||||
let act_num3 = Arc::clone(&num3);
|
||||
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
let mw1 = MiddlewareTest {
|
||||
start: Arc::clone(&act_num1),
|
||||
response: Arc::clone(&act_num2),
|
||||
finish: Arc::clone(&act_num3),
|
||||
};
|
||||
App::new().scope("/scope", |scope| {
|
||||
scope
|
||||
.middleware(mw1)
|
||||
.middleware(MiddlewareAsyncWithErr)
|
||||
.resource("/test", |r| r.h(|_| HttpResponse::Ok()))
|
||||
})
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/scope/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resource_middleware_chain_with_error() {
|
||||
let num1 = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = Arc::new(AtomicUsize::new(0));
|
||||
let num3 = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let act_num1 = Arc::clone(&num1);
|
||||
let act_num2 = Arc::clone(&num2);
|
||||
let act_num3 = Arc::clone(&num3);
|
||||
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
let mw1 = MiddlewareTest {
|
||||
start: Arc::clone(&act_num1),
|
||||
response: Arc::clone(&act_num2),
|
||||
finish: Arc::clone(&act_num3),
|
||||
};
|
||||
App::new().resource("/test", move |r| {
|
||||
r.middleware(mw1);
|
||||
r.middleware(MiddlewareWithErr);
|
||||
r.h(|_| HttpResponse::Ok());
|
||||
})
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resource_middleware_async_chain_with_error() {
|
||||
let num1 = Arc::new(AtomicUsize::new(0));
|
||||
let num2 = Arc::new(AtomicUsize::new(0));
|
||||
let num3 = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let act_num1 = Arc::clone(&num1);
|
||||
let act_num2 = Arc::clone(&num2);
|
||||
let act_num3 = Arc::clone(&num3);
|
||||
|
||||
let mut srv = test::TestServer::with_factory(move || {
|
||||
let mw1 = MiddlewareTest {
|
||||
start: Arc::clone(&act_num1),
|
||||
response: Arc::clone(&act_num2),
|
||||
finish: Arc::clone(&act_num3),
|
||||
};
|
||||
App::new().resource("/test", move |r| {
|
||||
r.middleware(mw1);
|
||||
r.middleware(MiddlewareAsyncWithErr);
|
||||
r.h(|_| HttpResponse::Ok());
|
||||
})
|
||||
});
|
||||
|
||||
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
|
||||
assert_eq!(num1.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num2.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(num3.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
@ -54,6 +54,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
|
||||
Hello World Hello World Hello World Hello World Hello World";
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn test_start() {
|
||||
let _ = test::TestServer::unused_addr();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
@ -86,12 +87,17 @@ fn test_start() {
|
||||
// pause
|
||||
let _ = srv_addr.send(server::PauseServer).wait();
|
||||
thread::sleep(time::Duration::from_millis(200));
|
||||
assert!(net::TcpStream::connect(addr).is_err());
|
||||
{
|
||||
let req = client::ClientRequest::get(format!("http://{}/", addr).as_str())
|
||||
.timeout(time::Duration::from_millis(200))
|
||||
.finish()
|
||||
.unwrap();
|
||||
assert!(sys.run_until_complete(req.send()).is_err());
|
||||
}
|
||||
|
||||
// resume
|
||||
let _ = srv_addr.send(server::ResumeServer).wait();
|
||||
thread::sleep(time::Duration::from_millis(200));
|
||||
|
||||
thread::sleep(time::Duration::from_millis(400));
|
||||
{
|
||||
let req = client::ClientRequest::get(format!("http://{}/", addr).as_str())
|
||||
.finish()
|
||||
|
Reference in New Issue
Block a user