1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-08-07 15:32:57 +02:00

Compare commits

...

20 Commits

Author SHA1 Message Date
Nikolay Kim
39f4b2b39e Merge branch 'master' of github.com:actix/actix-web 2020-01-10 11:28:58 +06:00
Nikolay Kim
f6ff056b8a Fix panic with already borrowed: BorrowMutError #1263 2020-01-10 11:26:54 +06:00
Yuki Okushi
51ab4fb73d Tweak actions to use cache and not to be stuck on the way (#1264) 2020-01-10 03:30:45 +09:00
linkmauve
f5fd6bc49f Fix actix-http examples (#1259)
Fix actix-http examples
2020-01-07 00:15:04 +09:00
Jeremy Wright
2803fcbe22 Small grammaritical update to lib.rs (#1248) 2020-01-03 08:45:17 +06:00
Nikolay Kim
67793c5d92 add ssl feature migration 2019-12-30 21:22:04 +06:00
Jonathan Brookins
bcb5086c91 Added 2.0.0 rustls feature name change (#1244) 2019-12-30 21:16:04 +06:00
wojciechkepka
7bd2270290 Fix link to example in readme.md (#1236)
* Fix link to example in readme.md

* Add links to openssl and rustls examples

* Rustls should be uppercase
2019-12-26 19:42:07 +09:00
Nikolay Kim
a4ad5e6b69 update timeouts for test server 2019-12-25 20:52:20 +04:00
Nikolay Kim
6db909a3e7 update migration 2019-12-25 20:27:30 +04:00
Nikolay Kim
642ae161c0 prep actix-web release 2019-12-25 20:21:00 +04:00
Nikolay Kim
7b3c99b933 prep actix-framed release 2019-12-25 20:17:22 +04:00
Nikolay Kim
f86ce0390e allow to specify multi pattern for resources 2019-12-25 20:14:44 +04:00
Nikolay Kim
7882f545e5 Allow to gracefully stop test server via TestServer::stop() 2019-12-25 12:10:48 +04:00
Nikolay Kim
1c75e6876b update migration 2019-12-22 17:16:07 +04:00
Nikolay Kim
6a0cd2dced Rename HttpServer::start() to HttpServer::run() 2019-12-22 17:12:22 +04:00
Nikolay Kim
c7f3915779 update actix-service dep 2019-12-22 16:39:25 +04:00
Yuki Okushi
f45db1f909 Enable GitHub Actions and fix file URL behavior (#1232)
* Use GitHub Actions

* Fix unused imports on Windows

* Fix test for Windows

* Stop to run CI for i686-pc-windows-msvc for now

* Use `/` instead of `\` on Windows

* Add entry to changelog

* Prepare actix-files release
2019-12-22 16:43:41 +09:00
Darin
3751a4018e fixed test::init_service api docs (missing await) (#1230) 2019-12-21 08:47:18 +06:00
Nikolay Kim
0cb1b0642f add test server data test 2019-12-20 23:18:59 +06:00
47 changed files with 511 additions and 192 deletions

59
.github/workflows/macos.yml vendored Normal file
View File

@@ -0,0 +1,59 @@
name: CI (macOS)
on: [push, pull_request]
jobs:
build_and_test:
strategy:
fail-fast: false
matrix:
version:
- stable
- nightly
name: ${{ matrix.version }} - x86_64-apple-darwin
runs-on: macOS-latest
steps:
- uses: actions/checkout@master
- name: Install ${{ matrix.version }}
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.version }}-x86_64-apple-darwin
profile: minimal
override: true
- name: Generate Cargo.lock
uses: actions-rs/cargo@v1
with:
command: update
- name: Cache cargo registry
uses: actions/cache@v1
with:
path: ~/.cargo/registry
key: ${{ matrix.version }}-x86_64-apple-darwin-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo index
uses: actions/cache@v1
with:
path: ~/.cargo/git
key: ${{ matrix.version }}-x86_64-apple-darwin-cargo-index-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo build
uses: actions/cache@v1
with:
path: target
key: ${{ matrix.version }}-x86_64-apple-darwin-cargo-build-${{ hashFiles('**/Cargo.lock') }}
- name: check build
uses: actions-rs/cargo@v1
with:
command: check
args: --all --bins --examples --tests
- name: tests
uses: actions-rs/cargo@v1
with:
command: test
args: --all --all-features --no-fail-fast -- --nocapture
--skip=test_h2_content_length
--skip=test_reading_deflate_encoding_large_random_rustls

79
.github/workflows/windows.yml vendored Normal file
View File

@@ -0,0 +1,79 @@
name: CI (Windows)
on: [push, pull_request]
env:
VCPKGRS_DYNAMIC: 1
jobs:
build_and_test:
strategy:
fail-fast: false
matrix:
version:
- stable
- nightly
name: ${{ matrix.version }} - x86_64-pc-windows-msvc
runs-on: windows-latest
steps:
- uses: actions/checkout@master
- name: Install ${{ matrix.version }}
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.version }}-x86_64-pc-windows-msvc
profile: minimal
override: true
- name: Generate Cargo.lock
uses: actions-rs/cargo@v1
with:
command: update
- name: Cache cargo registry
uses: actions/cache@v1
with:
path: ~/.cargo/registry
key: ${{ matrix.version }}-x86_64-pc-windows-msvc-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo index
uses: actions/cache@v1
with:
path: ~/.cargo/git
key: ${{ matrix.version }}-x86_64-pc-windows-msvc-cargo-index-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo build
uses: actions/cache@v1
with:
path: target
key: ${{ matrix.version }}-x86_64-pc-windows-msvc-cargo-build-${{ hashFiles('**/Cargo.lock') }}
- name: Cache vcpkg package
uses: actions/cache@v1
id: cache-vcpkg
with:
path: C:\vcpkg
key: windows_x64-${{ matrix.version }}-vcpkg
- name: Install OpenSSL
if: steps.cache-vcpkg.outputs.cache-hit != 'true'
run: |
vcpkg integrate install
vcpkg install openssl:x64-windows
- name: check build
uses: actions-rs/cargo@v1
with:
command: check
args: --all --bins --examples --tests
- name: tests
uses: actions-rs/cargo@v1
with:
command: test
args: --all --all-features --no-fail-fast -- --nocapture
--skip=test_h2_content_length
--skip=test_reading_deflate_encoding_large_random_rustls
--skip=test_params
--skip=test_simple
--skip=test_expect_continue
--skip=test_http10_keepalive
--skip=test_slow_request

View File

@@ -1,5 +1,15 @@
# Changes # Changes
## [2.0.0] - 2019-12-25
### Changed
* Rename `HttpServer::start()` to `HttpServer::run()`
* Allow to gracefully stop test server via `TestServer::stop()`
* Allow to specify multi-patterns for resources
## [2.0.0-rc] - 2019-12-20 ## [2.0.0-rc] - 2019-12-20
### Changed ### Changed

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-web" name = "actix-web"
version = "2.0.0-rc" version = "2.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust." description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
readme = "README.md" readme = "README.md"
@@ -60,18 +60,18 @@ rustls = ["actix-tls/rustls", "awc/rustls", "rust-tls"]
[dependencies] [dependencies]
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-service = "1.0.0" actix-service = "1.0.1"
actix-utils = "1.0.3" actix-utils = "1.0.4"
actix-router = "0.2.0" actix-router = "0.2.1"
actix-rt = "1.0.0" actix-rt = "1.0.0"
actix-server = "1.0.0" actix-server = "1.0.0"
actix-testing = "1.0.0" actix-testing = "1.0.0"
actix-macros = "0.1.0" actix-macros = "0.1.0"
actix-threadpool = "0.3.0" actix-threadpool = "0.3.1"
actix-tls = "1.0.0" actix-tls = "1.0.0"
actix-web-codegen = "0.2.0" actix-web-codegen = "0.2.0"
actix-http = "1.0.0" actix-http = "1.0.1"
awc = { version = "1.0.1", default-features = false } awc = { version = "1.0.1", default-features = false }
bytes = "0.5.3" bytes = "0.5.3"
@@ -93,7 +93,7 @@ open-ssl = { version="0.10", package = "openssl", optional = true }
rust-tls = { version = "0.16.0", package = "rustls", optional = true } rust-tls = { version = "0.16.0", package = "rustls", optional = true }
[dev-dependencies] [dev-dependencies]
actix = "0.9.0-alpha.2" actix = "0.9.0"
rand = "0.7" rand = "0.7"
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"
@@ -115,4 +115,4 @@ actix-identity = { path = "actix-identity" }
actix-session = { path = "actix-session" } actix-session = { path = "actix-session" }
actix-files = { path = "actix-files" } actix-files = { path = "actix-files" }
actix-multipart = { path = "actix-multipart" } actix-multipart = { path = "actix-multipart" }
awc = { path = "awc" } awc = { path = "awc" }

View File

@@ -1,15 +1,49 @@
## 2.0.0 ## 2.0.0
* `HttpServer::start()` renamed to `HttpServer::run()`. It also possible to
`.await` on `run` method result, in that case it awaits server exit.
* `App::register_data()` renamed to `App::app_data()` and accepts any type `T: 'static`. * `App::register_data()` renamed to `App::app_data()` and accepts any type `T: 'static`.
Stored data is available via `HttpRequest::app_data()` method at runtime. Stored data is available via `HttpRequest::app_data()` method at runtime.
* Extractor configuration must be registered with `App::app_data()` instead of `App::data()` * Extractor configuration must be registered with `App::app_data()` instead of `App::data()`
* Sync handlers has been removed. `.to_async()` method has been renamed to `.to()` * Sync handlers has been removed. `.to_async()` method has been renamed to `.to()`
replace `fn` with `async fn` to convert sync handler to async replace `fn` with `async fn` to convert sync handler to async
* `TestServer::new()` renamed to `TestServer::start()` * `actix_http_test::TestServer` moved to `actix_web::test` module. To start
test server use `test::start()` or `test_start_with_config()` methods
* `ResponseError` trait has been reafctored. `ResponseError::error_response()` renders
http response.
* Feature `rust-tls` renamed to `rustls`
instead of
```rust
actix-web = { version = "2.0.0", features = ["rust-tls"] }
```
use
```rust
actix-web = { version = "2.0.0", features = ["rustls"] }
```
* Feature `ssl` renamed to `openssl`
instead of
```rust
actix-web = { version = "2.0.0", features = ["ssl"] }
```
use
```rust
actix-web = { version = "2.0.0", features = ["openssl"] }
```
## 1.0.1 ## 1.0.1

View File

@@ -53,7 +53,7 @@ async fn index(info: web::Path<(u32, String)>) -> impl Responder {
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index)) HttpServer::new(|| App::new().service(index))
.bind("127.0.0.1:8080")? .bind("127.0.0.1:8080")?
.start() .run()
.await .await
} }
``` ```
@@ -68,7 +68,8 @@ async fn main() -> std::io::Result<()> {
[Askama](https://github.com/actix/examples/tree/master/template_askama/) templates [Askama](https://github.com/actix/examples/tree/master/template_askama/) templates
* [Diesel integration](https://github.com/actix/examples/tree/master/diesel/) * [Diesel integration](https://github.com/actix/examples/tree/master/diesel/)
* [r2d2](https://github.com/actix/examples/tree/master/r2d2/) * [r2d2](https://github.com/actix/examples/tree/master/r2d2/)
* [SSL / HTTP/2.0](https://github.com/actix/examples/tree/master/tls/) * [OpenSSL](https://github.com/actix/examples/tree/master/openssl/)
* [Rustls](https://github.com/actix/examples/tree/master/rustls/)
* [Tcp/Websocket chat](https://github.com/actix/examples/tree/master/websocket-chat/) * [Tcp/Websocket chat](https://github.com/actix/examples/tree/master/websocket-chat/)
* [Json](https://github.com/actix/examples/tree/master/json/) * [Json](https://github.com/actix/examples/tree/master/json/)

View File

@@ -18,7 +18,7 @@ path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = "2.0.0-rc" actix-web = "2.0.0-rc"
actix-service = "1.0.0" actix-service = "1.0.1"
derive_more = "0.99.2" derive_more = "0.99.2"
futures = "0.3.1" futures = "0.3.1"

View File

@@ -814,7 +814,7 @@ where
res res
} }
} }
.boxed_local(), .boxed_local(),
) )
} }
} }

View File

@@ -1,5 +1,9 @@
# Changes # Changes
## [0.2.1] - 2019-12-22
* Use the same format for file URLs regardless of platforms
## [0.2.0] - 2019-12-20 ## [0.2.0] - 2019-12-20
* Fix BodyEncoding trait import #1220 * Fix BodyEncoding trait import #1220

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-files" name = "actix-files"
version = "0.2.0" version = "0.2.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Static files support for actix web." description = "Static files support for actix web."
readme = "README.md" readme = "README.md"
@@ -20,7 +20,7 @@ path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "2.0.0-rc", default-features = false } actix-web = { version = "2.0.0-rc", default-features = false }
actix-http = "1.0.1" actix-http = "1.0.1"
actix-service = "1.0.0" actix-service = "1.0.1"
bitflags = "1" bitflags = "1"
bytes = "0.5.3" bytes = "0.5.3"
futures = "0.3.1" futures = "0.3.1"

View File

@@ -155,7 +155,7 @@ impl Directory {
// show file url as relative to static path // show file url as relative to static path
macro_rules! encode_file_url { macro_rules! encode_file_url {
($path:ident) => { ($path:ident) => {
utf8_percent_encode(&$path.to_string_lossy(), CONTROLS) utf8_percent_encode(&$path, CONTROLS)
}; };
} }
@@ -178,7 +178,10 @@ fn directory_listing(
if dir.is_visible(&entry) { if dir.is_visible(&entry) {
let entry = entry.unwrap(); let entry = entry.unwrap();
let p = match entry.path().strip_prefix(&dir.path) { let p = match entry.path().strip_prefix(&dir.path) {
Ok(p) => base.join(p), Ok(p) if cfg!(windows) => {
base.join(p).to_string_lossy().replace("\\", "/")
}
Ok(p) => base.join(p).to_string_lossy().into_owned(),
Err(_) => continue, Err(_) => continue,
}; };

View File

@@ -13,7 +13,6 @@ categories = ["network-programming", "asynchronous",
"web-programming::websocket"] "web-programming::websocket"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
edition = "2018" edition = "2018"
workspace =".."
[lib] [lib]
name = "actix_framed" name = "actix_framed"
@@ -21,10 +20,10 @@ path = "src/lib.rs"
[dependencies] [dependencies]
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-service = "1.0.0" actix-service = "1.0.1"
actix-router = "0.2.0" actix-router = "0.2.1"
actix-rt = "1.0.0" actix-rt = "1.0.0"
actix-http = "1.0.0" actix-http = "1.0.1"
bytes = "0.5.3" bytes = "0.5.3"
futures = "0.3.1" futures = "0.3.1"

View File

@@ -1,5 +1,9 @@
# Changes # Changes
## [0.3.0] - 2019-12-25
* Migrate to actix-http 1.0
## [0.2.1] - 2019-07-20 ## [0.2.1] - 2019-07-20
* Remove unneeded actix-utils dependency * Remove unneeded actix-utils dependency

View File

@@ -66,7 +66,7 @@ where
service service
}) })
} }
.boxed_local() .boxed_local()
} }
} }

View File

@@ -154,6 +154,6 @@ where
} }
Ok(()) Ok(())
} }
.boxed_local() .boxed_local()
} }
} }

View File

@@ -40,7 +40,7 @@ failure = ["fail-ure"]
secure-cookies = ["ring"] secure-cookies = ["ring"]
[dependencies] [dependencies]
actix-service = "1.0.0" actix-service = "1.0.1"
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-connect = "1.0.1" actix-connect = "1.0.1"
actix-utils = "1.0.3" actix-utils = "1.0.3"

View File

@@ -7,7 +7,8 @@ use futures::StreamExt;
use http::header::HeaderValue; use http::header::HeaderValue;
use log::info; use log::info;
fn main() -> io::Result<()> { #[actix_rt::main]
async fn main() -> io::Result<()> {
env::set_var("RUST_LOG", "echo=info"); env::set_var("RUST_LOG", "echo=info");
env_logger::init(); env_logger::init();
@@ -37,4 +38,5 @@ fn main() -> io::Result<()> {
.tcp() .tcp()
})? })?
.run() .run()
.await
} }

View File

@@ -19,7 +19,8 @@ async fn handle_request(mut req: Request) -> Result<Response, Error> {
.body(body)) .body(body))
} }
fn main() -> io::Result<()> { #[actix_rt::main]
async fn main() -> io::Result<()> {
env::set_var("RUST_LOG", "echo=info"); env::set_var("RUST_LOG", "echo=info");
env_logger::init(); env_logger::init();
@@ -28,4 +29,5 @@ fn main() -> io::Result<()> {
HttpService::build().finish(handle_request).tcp() HttpService::build().finish(handle_request).tcp()
})? })?
.run() .run()
.await
} }

View File

@@ -6,7 +6,8 @@ use futures::future;
use http::header::HeaderValue; use http::header::HeaderValue;
use log::info; use log::info;
fn main() -> io::Result<()> { #[actix_rt::main]
async fn main() -> io::Result<()> {
env::set_var("RUST_LOG", "hello_world=info"); env::set_var("RUST_LOG", "hello_world=info");
env_logger::init(); env_logger::init();
@@ -24,4 +25,5 @@ fn main() -> io::Result<()> {
.tcp() .tcp()
})? })?
.run() .run()
.await
} }

View File

@@ -1,5 +1,9 @@
# Changes # Changes
## [0.2.1] - 2020-01-10
* Fix panic with already borrowed: BorrowMutError #1263
## [0.2.0] - 2019-12-20 ## [0.2.0] - 2019-12-20
* Use actix-web 2.0 * Use actix-web 2.0

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-identity" name = "actix-identity"
version = "0.2.0" version = "0.2.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Identity service for actix web framework." description = "Identity service for actix web framework."
readme = "README.md" readme = "README.md"
@@ -10,15 +10,14 @@ repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-identity/" documentation = "https://docs.rs/actix-identity/"
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
edition = "2018" edition = "2018"
workspace = ".."
[lib] [lib]
name = "actix_identity" name = "actix_identity"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "2.0.0-rc", default-features = false, features = ["secure-cookies"] } actix-web = { version = "2.0.0", default-features = false, features = ["secure-cookies"] }
actix-service = "1.0.0" actix-service = "1.0.2"
futures = "0.3.1" futures = "0.3.1"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"

View File

@@ -251,6 +251,15 @@ pub struct IdentityServiceMiddleware<S, T> {
service: Rc<RefCell<S>>, service: Rc<RefCell<S>>,
} }
impl<S, T> Clone for IdentityServiceMiddleware<S, T> {
fn clone(&self) -> Self {
Self {
backend: self.backend.clone(),
service: self.service.clone(),
}
}
}
impl<S, T, B> Service for IdentityServiceMiddleware<S, T> impl<S, T, B> Service for IdentityServiceMiddleware<S, T>
where where
B: 'static, B: 'static,
@@ -279,7 +288,9 @@ where
req.extensions_mut() req.extensions_mut()
.insert(IdentityItem { id, changed: false }); .insert(IdentityItem { id, changed: false });
let mut res = srv.borrow_mut().call(req).await?; // https://github.com/actix/actix-web/issues/1263
let fut = { srv.borrow_mut().call(req) };
let mut res = fut.await?;
let id = res.request().extensions_mut().remove::<IdentityItem>(); let id = res.request().extensions_mut().remove::<IdentityItem>();
if let Some(id) = id { if let Some(id) = id {
@@ -294,7 +305,7 @@ where
Err(err) => Ok(req.error_response(err)), Err(err) => Ok(req.error_response(err)),
} }
} }
.boxed_local() .boxed_local()
} }
} }
@@ -606,9 +617,10 @@ mod tests {
use std::borrow::Borrow; use std::borrow::Borrow;
use super::*; use super::*;
use actix_service::into_service;
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::test::{self, TestRequest}; use actix_web::test::{self, TestRequest};
use actix_web::{web, App, Error, HttpResponse}; use actix_web::{error, web, App, Error, HttpResponse};
const COOKIE_KEY_MASTER: [u8; 32] = [0; 32]; const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
const COOKIE_NAME: &'static str = "actix_auth"; const COOKIE_NAME: &'static str = "actix_auth";
@@ -1045,6 +1057,7 @@ mod tests {
assert_logged_in(resp, Some(COOKIE_LOGIN)).await; assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
} }
// https://github.com/actix/actix-web/issues/1263
#[actix_rt::test] #[actix_rt::test]
async fn test_identity_cookie_updated_on_visit_deadline() { async fn test_identity_cookie_updated_on_visit_deadline() {
let mut srv = create_identity_server(|c| { let mut srv = create_identity_server(|c| {
@@ -1069,4 +1082,47 @@ mod tests {
); );
assert_logged_in(resp, Some(COOKIE_LOGIN)).await; assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
} }
#[actix_rt::test]
async fn test_borrowed_mut_error() {
use futures::future::{lazy, ok, Ready};
struct Ident;
impl IdentityPolicy for Ident {
type Future = Ready<Result<Option<String>, Error>>;
type ResponseFuture = Ready<Result<(), Error>>;
fn from_request(&self, _: &mut ServiceRequest) -> Self::Future {
ok(Some("test".to_string()))
}
fn to_response<B>(
&self,
_: Option<String>,
_: bool,
_: &mut ServiceResponse<B>,
) -> Self::ResponseFuture {
ok(())
}
}
let mut srv = IdentityServiceMiddleware {
backend: Rc::new(Ident),
service: Rc::new(RefCell::new(into_service(|_: ServiceRequest| {
async move {
actix_rt::time::delay_for(std::time::Duration::from_secs(100)).await;
Err::<ServiceResponse, _>(error::ErrorBadRequest("error"))
}
}))),
};
let mut srv2 = srv.clone();
let req = TestRequest::default().to_srv_request();
actix_rt::spawn(async move {
let _ = srv2.call(req).await;
});
actix_rt::time::delay_for(std::time::Duration::from_millis(50)).await;
let _ = lazy(|cx| srv.poll_ready(cx)).await;
}
} }

View File

@@ -17,7 +17,7 @@ path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "2.0.0-rc", default-features = false } actix-web = { version = "2.0.0-rc", default-features = false }
actix-service = "1.0.0" actix-service = "1.0.1"
actix-utils = "1.0.3" actix-utils = "1.0.3"
bytes = "0.5.3" bytes = "0.5.3"
derive_more = "0.99.2" derive_more = "0.99.2"

View File

@@ -23,7 +23,7 @@ cookie-session = ["actix-web/secure-cookies"]
[dependencies] [dependencies]
actix-web = "2.0.0-rc" actix-web = "2.0.0-rc"
actix-service = "1.0.0" actix-service = "1.0.1"
bytes = "0.5.3" bytes = "0.5.3"
derive_more = "0.99.2" derive_more = "0.99.2"
futures = "0.3.1" futures = "0.3.1"

View File

@@ -354,7 +354,7 @@ where
} }
}) })
} }
.boxed_local() .boxed_local()
} }
} }

View File

@@ -37,7 +37,7 @@
//! ) //! )
//! .service(web::resource("/").to(|| HttpResponse::Ok()))) //! .service(web::resource("/").to(|| HttpResponse::Ok())))
//! .bind("127.0.0.1:59880")? //! .bind("127.0.0.1:59880")?
//! .start() //! .run()
//! .await //! .await
//! } //! }
//! ``` //! ```

View File

@@ -35,7 +35,7 @@ compress = ["actix-http/compress"]
[dependencies] [dependencies]
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-service = "1.0.0" actix-service = "1.0.1"
actix-http = "1.0.0" actix-http = "1.0.0"
actix-rt = "1.0.0" actix-rt = "1.0.0"

View File

@@ -14,7 +14,7 @@ use rand::Rng;
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory, IntoServiceFactory}; use actix_service::{map_config, pipeline_factory};
use actix_web::dev::{AppConfig, BodyEncoding}; use actix_web::dev::{AppConfig, BodyEncoding};
use actix_web::http::Cookie; use actix_web::http::Cookie;
use actix_web::middleware::Compress; use actix_web::middleware::Compress;
@@ -172,8 +172,7 @@ async fn test_connection_reuse() {
.and_then( .and_then(
HttpService::new(map_config( HttpService::new(map_config(
App::new() App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))) .service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
.into_factory(),
|_| AppConfig::default(), |_| AppConfig::default(),
)) ))
.tcp(), .tcp(),
@@ -210,8 +209,7 @@ async fn test_connection_force_close() {
.and_then( .and_then(
HttpService::new(map_config( HttpService::new(map_config(
App::new() App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))) .service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
.into_factory(),
|_| AppConfig::default(), |_| AppConfig::default(),
)) ))
.tcp(), .tcp(),
@@ -239,25 +237,23 @@ async fn test_connection_server_close() {
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
let srv = let srv = test_server(move || {
test_server(move || { let num2 = num2.clone();
let num2 = num2.clone(); pipeline_factory(move |io| {
pipeline_factory(move |io| { num2.fetch_add(1, Ordering::Relaxed);
num2.fetch_add(1, Ordering::Relaxed); ok(io)
ok(io) })
}) .and_then(
.and_then( HttpService::new(map_config(
HttpService::new(map_config( App::new().service(
App::new() web::resource("/")
.service(web::resource("/").route(web::to(|| { .route(web::to(|| HttpResponse::Ok().force_close().finish())),
HttpResponse::Ok().force_close().finish() ),
}))) |_| AppConfig::default(),
.into_factory(), ))
|_| AppConfig::default(), .tcp(),
)) )
.tcp(), });
)
});
let client = awc::Client::default(); let client = awc::Client::default();
@@ -288,12 +284,9 @@ async fn test_connection_wait_queue() {
}) })
.and_then( .and_then(
HttpService::new(map_config( HttpService::new(map_config(
App::new() App::new().service(
.service( web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
web::resource("/") ),
.route(web::to(|| HttpResponse::Ok().body(STR))),
)
.into_factory(),
|_| AppConfig::default(), |_| AppConfig::default(),
)) ))
.tcp(), .tcp(),
@@ -330,25 +323,23 @@ async fn test_connection_wait_queue_force_close() {
let num = Arc::new(AtomicUsize::new(0)); let num = Arc::new(AtomicUsize::new(0));
let num2 = num.clone(); let num2 = num.clone();
let srv = let srv = test_server(move || {
test_server(move || { let num2 = num2.clone();
let num2 = num2.clone(); pipeline_factory(move |io| {
pipeline_factory(move |io| { num2.fetch_add(1, Ordering::Relaxed);
num2.fetch_add(1, Ordering::Relaxed); ok(io)
ok(io) })
}) .and_then(
.and_then( HttpService::new(map_config(
HttpService::new(map_config( App::new().service(
App::new() web::resource("/")
.service(web::resource("/").route(web::to(|| { .route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
HttpResponse::Ok().force_close().body(STR) ),
}))) |_| AppConfig::default(),
.into_factory(), ))
|_| AppConfig::default(), .tcp(),
)) )
.tcp(), });
)
});
let client = awc::Client::build() let client = awc::Client::build()
.connector(awc::Connector::new().limit(1).finish()) .connector(awc::Connector::new().limit(1).finish())

View File

@@ -4,7 +4,7 @@ use std::sync::Arc;
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory, IntoServiceFactory, ServiceFactory}; use actix_service::{map_config, pipeline_factory, ServiceFactory};
use actix_web::http::Version; use actix_web::http::Version;
use actix_web::{dev::AppConfig, web, App, HttpResponse}; use actix_web::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok; use futures::future::ok;
@@ -63,11 +63,9 @@ async fn _test_connection_reuse_h2() {
.and_then( .and_then(
HttpService::build() HttpService::build()
.h2(map_config( .h2(map_config(
App::new() App::new().service(
.service( web::resource("/").route(web::to(|| HttpResponse::Ok())),
web::resource("/").route(web::to(|| HttpResponse::Ok())), ),
)
.into_factory(),
|_| AppConfig::default(), |_| AppConfig::default(),
)) ))
.openssl(ssl_acceptor()) .openssl(ssl_acceptor())

View File

@@ -4,7 +4,7 @@ use std::sync::Arc;
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::test_server; use actix_http_test::test_server;
use actix_service::{map_config, pipeline_factory, IntoServiceFactory, ServiceFactory}; use actix_service::{map_config, pipeline_factory, ServiceFactory};
use actix_web::http::Version; use actix_web::http::Version;
use actix_web::{dev::AppConfig, web, App, HttpResponse}; use actix_web::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok; use futures::future::ok;
@@ -45,11 +45,9 @@ async fn test_connection_reuse_h2() {
.and_then( .and_then(
HttpService::build() HttpService::build()
.h2(map_config( .h2(map_config(
App::new() App::new().service(
.service( web::resource("/").route(web::to(|| HttpResponse::Ok())),
web::resource("/").route(web::to(|| HttpResponse::Ok())), ),
)
.into_factory(),
|_| AppConfig::default(), |_| AppConfig::default(),
)) ))
.openssl(ssl_acceptor()) .openssl(ssl_acceptor())

View File

@@ -42,6 +42,6 @@ async fn main() -> std::io::Result<()> {
}) })
.bind("127.0.0.1:8080")? .bind("127.0.0.1:8080")?
.workers(1) .workers(1)
.start() .run()
.await .await
} }

View File

@@ -45,7 +45,7 @@ async fn main() -> std::io::Result<()> {
}) })
.bind_uds("/Users/fafhrd91/uds-test")? .bind_uds("/Users/fafhrd91/uds-test")?
.workers(1) .workers(1)
.start() .run()
.await .await
} }

View File

@@ -136,10 +136,11 @@ impl<T: 'static> DataFactory for Data<T> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_service::Service; use actix_service::Service;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*; use super::*;
use crate::http::StatusCode; use crate::http::StatusCode;
use crate::test::{init_service, TestRequest}; use crate::test::{self, init_service, TestRequest};
use crate::{web, App, HttpResponse}; use crate::{web, App, HttpResponse};
#[actix_rt::test] #[actix_rt::test]
@@ -234,4 +235,47 @@ mod tests {
let resp = srv.call(req).await.unwrap(); let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
#[actix_rt::test]
async fn test_data_drop() {
struct TestData(Arc<AtomicUsize>);
impl TestData {
fn new(inner: Arc<AtomicUsize>) -> Self {
let _ = inner.fetch_add(1, Ordering::SeqCst);
Self(inner)
}
}
impl Clone for TestData {
fn clone(&self) -> Self {
let inner = self.0.clone();
let _ = inner.fetch_add(1, Ordering::SeqCst);
Self(inner)
}
}
impl Drop for TestData {
fn drop(&mut self) {
let _ = self.0.fetch_sub(1, Ordering::SeqCst);
}
}
let num = Arc::new(AtomicUsize::new(0));
let data = TestData::new(num.clone());
assert_eq!(num.load(Ordering::SeqCst), 1);
let srv = test::start(move || {
let data = data.clone();
App::new()
.data(data)
.service(web::resource("/").to(|_data: Data<TestData>| async { "ok" }))
});
assert!(srv.get("/").send().await.unwrap().status().is_success());
srv.stop().await;
assert_eq!(num.load(Ordering::SeqCst), 0);
}
} }

View File

@@ -20,7 +20,7 @@
//! web::resource("/{name}/{id}/index.html").to(index)) //! web::resource("/{name}/{id}/index.html").to(index))
//! ) //! )
//! .bind("127.0.0.1:8080")? //! .bind("127.0.0.1:8080")?
//! .start() //! .run()
//! .await //! .await
//! } //! }
//! ``` //! ```
@@ -47,7 +47,7 @@
//! configure servers. //! configure servers.
//! //!
//! * [web](web/index.html): This module //! * [web](web/index.html): This module
//! provide essentials helper functions and types for application registration. //! provides essential helper functions and types for application registration.
//! //!
//! * [HttpRequest](struct.HttpRequest.html) and //! * [HttpRequest](struct.HttpRequest.html) and
//! [HttpResponse](struct.HttpResponse.html): These structs //! [HttpResponse](struct.HttpResponse.html): These structs
@@ -151,12 +151,13 @@ pub mod dev {
pub use actix_server::Server; pub use actix_server::Server;
pub use actix_service::{Service, Transform}; pub use actix_service::{Service, Transform};
pub(crate) fn insert_slash(path: &str) -> String { pub(crate) fn insert_slash(mut patterns: Vec<String>) -> Vec<String> {
let mut path = path.to_owned(); for path in &mut patterns {
if !path.is_empty() && !path.starts_with('/') { if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/'); path.insert(0, '/');
}; };
path }
patterns
} }
use crate::http::header::ContentEncoding; use crate::http::header::ContentEncoding;

View File

@@ -150,7 +150,7 @@ where
} }
Ok(res) Ok(res)
} }
.boxed_local() .boxed_local()
} }
} }

View File

@@ -140,7 +140,7 @@ where
Ok(res) Ok(res)
} }
} }
.boxed_local() .boxed_local()
} }
} }

View File

@@ -6,6 +6,7 @@ use std::rc::Rc;
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use actix_http::{Error, Extensions, Response}; use actix_http::{Error, Extensions, Response};
use actix_router::IntoPattern;
use actix_service::boxed::{self, BoxService, BoxServiceFactory}; use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{ use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform, apply, apply_fn_factory, IntoServiceFactory, Service, ServiceFactory, Transform,
@@ -48,7 +49,7 @@ type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Err
/// Default behavior could be overriden with `default_resource()` method. /// Default behavior could be overriden with `default_resource()` method.
pub struct Resource<T = ResourceEndpoint> { pub struct Resource<T = ResourceEndpoint> {
endpoint: T, endpoint: T,
rdef: String, rdef: Vec<String>,
name: Option<String>, name: Option<String>,
routes: Vec<Route>, routes: Vec<Route>,
data: Option<Extensions>, data: Option<Extensions>,
@@ -58,12 +59,12 @@ pub struct Resource<T = ResourceEndpoint> {
} }
impl Resource { impl Resource {
pub fn new(path: &str) -> Resource { pub fn new<T: IntoPattern>(path: T) -> Resource {
let fref = Rc::new(RefCell::new(None)); let fref = Rc::new(RefCell::new(None));
Resource { Resource {
routes: Vec::new(), routes: Vec::new(),
rdef: path.to_string(), rdef: path.patterns(),
name: None, name: None,
endpoint: ResourceEndpoint::new(fref.clone()), endpoint: ResourceEndpoint::new(fref.clone()),
factory_ref: fref, factory_ref: fref,
@@ -381,9 +382,9 @@ where
Some(std::mem::replace(&mut self.guards, Vec::new())) Some(std::mem::replace(&mut self.guards, Vec::new()))
}; };
let mut rdef = if config.is_root() || !self.rdef.is_empty() { let mut rdef = if config.is_root() || !self.rdef.is_empty() {
ResourceDef::new(&insert_slash(&self.rdef)) ResourceDef::new(insert_slash(self.rdef.clone()))
} else { } else {
ResourceDef::new(&self.rdef) ResourceDef::new(self.rdef.clone())
}; };
if let Some(ref name) = self.name { if let Some(ref name) = self.name {
*rdef.name_mut() = name.clone(); *rdef.name_mut() = name.clone();
@@ -660,6 +661,23 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
#[actix_rt::test]
async fn test_pattern() {
let mut srv = init_service(
App::new().service(
web::resource(["/test", "/test2"])
.to(|| async { Ok::<_, Error>(HttpResponse::Ok()) }),
),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/test2").to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test] #[actix_rt::test]
async fn test_default_resource() { async fn test_default_resource() {
let mut srv = init_service( let mut srv = init_service(

View File

@@ -2,17 +2,19 @@ use std::marker::PhantomData;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::{fmt, io, net}; use std::{fmt, io, net};
use actix_http::{ use actix_http::{body::MessageBody, Error, HttpService, KeepAlive, Request, Response};
body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response,
};
use actix_server::{Server, ServerBuilder}; use actix_server::{Server, ServerBuilder};
use actix_service::{ use actix_service::{map_config, IntoServiceFactory, Service, ServiceFactory};
map_config, pipeline_factory, IntoServiceFactory, Service, ServiceFactory,
};
use futures::future::ok;
use net2::TcpBuilder; use net2::TcpBuilder;
#[cfg(unix)]
use actix_http::Protocol;
#[cfg(unix)]
use actix_service::pipeline_factory;
#[cfg(unix)]
use futures::future::ok;
#[cfg(feature = "openssl")] #[cfg(feature = "openssl")]
use actix_tls::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder}; use actix_tls::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
#[cfg(feature = "rustls")] #[cfg(feature = "rustls")]
@@ -36,21 +38,17 @@ struct Config {
/// ///
/// Create new http server with application factory. /// Create new http server with application factory.
/// ///
/// ```rust /// ```rust,no_run
/// use std::io;
/// use actix_web::{web, App, HttpResponse, HttpServer}; /// use actix_web::{web, App, HttpResponse, HttpServer};
/// ///
/// fn main() -> io::Result<()> { /// #[actix_rt::main]
/// let sys = actix_rt::System::new("example"); // <- create Actix runtime /// async fn main() -> std::io::Result<()> {
///
/// HttpServer::new( /// HttpServer::new(
/// || App::new() /// || App::new()
/// .service(web::resource("/").to(|| HttpResponse::Ok()))) /// .service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:59090")? /// .bind("127.0.0.1:59090")?
/// .start(); /// .run()
/// /// .await
/// # actix_rt::System::current().stop();
/// sys.run()
/// } /// }
/// ``` /// ```
pub struct HttpServer<F, I, S, B> pub struct HttpServer<F, I, S, B>
@@ -260,7 +258,7 @@ where
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.local_addr(addr) .local_addr(addr)
.finish(map_config(factory().into_factory(), move |_| cfg.clone())) .finish(map_config(factory(), move |_| cfg.clone()))
.tcp() .tcp()
}, },
)?; )?;
@@ -307,7 +305,7 @@ where
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown) .client_disconnect(c.client_shutdown)
.finish(map_config(factory().into_factory(), move |_| cfg.clone())) .finish(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone()) .openssl(acceptor.clone())
}, },
)?; )?;
@@ -354,7 +352,7 @@ where
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown) .client_disconnect(c.client_shutdown)
.finish(map_config(factory().into_factory(), move |_| cfg.clone())) .finish(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone()) .rustls(config.clone())
}, },
)?; )?;
@@ -477,9 +475,7 @@ where
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.finish(map_config(factory().into_factory(), move |_| { .finish(map_config(factory(), move |_| config.clone())),
config.clone()
})),
) )
})?; })?;
Ok(self) Ok(self)
@@ -521,9 +517,7 @@ where
HttpService::build() HttpService::build()
.keep_alive(c.keep_alive) .keep_alive(c.keep_alive)
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.finish(map_config(factory().into_factory(), move |_| { .finish(map_config(factory(), move |_| config.clone())),
config.clone()
})),
) )
}, },
)?; )?;
@@ -559,11 +553,11 @@ where
/// async fn main() -> io::Result<()> { /// async fn main() -> io::Result<()> {
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok()))) /// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0")? /// .bind("127.0.0.1:0")?
/// .start() /// .run()
/// .await /// .await
/// } /// }
/// ``` /// ```
pub fn start(self) -> Server { pub fn run(self) -> Server {
self.builder.start() self.builder.start()
} }
} }

View File

@@ -8,7 +8,7 @@ use actix_http::{
Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response, Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response,
ResponseHead, ResponseHead,
}; };
use actix_router::{Path, Resource, ResourceDef, Url}; use actix_router::{IntoPattern, Path, Resource, ResourceDef, Url};
use actix_service::{IntoServiceFactory, ServiceFactory}; use actix_service::{IntoServiceFactory, ServiceFactory};
use crate::config::{AppConfig, AppService}; use crate::config::{AppConfig, AppService};
@@ -422,16 +422,16 @@ impl<B: MessageBody> fmt::Debug for ServiceResponse<B> {
} }
pub struct WebService { pub struct WebService {
rdef: String, rdef: Vec<String>,
name: Option<String>, name: Option<String>,
guards: Vec<Box<dyn Guard>>, guards: Vec<Box<dyn Guard>>,
} }
impl WebService { impl WebService {
/// Create new `WebService` instance. /// Create new `WebService` instance.
pub fn new(path: &str) -> Self { pub fn new<T: IntoPattern>(path: T) -> Self {
WebService { WebService {
rdef: path.to_string(), rdef: path.patterns(),
name: None, name: None,
guards: Vec::new(), guards: Vec::new(),
} }
@@ -491,7 +491,7 @@ impl WebService {
struct WebServiceImpl<T> { struct WebServiceImpl<T> {
srv: T, srv: T,
rdef: String, rdef: Vec<String>,
name: Option<String>, name: Option<String>,
guards: Vec<Box<dyn Guard>>, guards: Vec<Box<dyn Guard>>,
} }
@@ -514,9 +514,9 @@ where
}; };
let mut rdef = if config.is_root() || !self.rdef.is_empty() { let mut rdef = if config.is_root() || !self.rdef.is_empty() {
ResourceDef::new(&insert_slash(&self.rdef)) ResourceDef::new(insert_slash(self.rdef))
} else { } else {
ResourceDef::new(&self.rdef) ResourceDef::new(self.rdef)
}; };
if let Some(ref name) = self.name { if let Some(ref name) = self.name {
*rdef.name_mut() = name.clone(); *rdef.name_mut() = name.clone();

View File

@@ -11,8 +11,7 @@ use actix_http::http::{Error as HttpError, Method, StatusCode, Uri, Version};
use actix_http::test::TestRequest as HttpTestRequest; use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request}; use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
use actix_router::{Path, ResourceDef, Url}; use actix_router::{Path, ResourceDef, Url};
use actix_rt::System; use actix_rt::{time::delay_for, System};
use actix_server::Server;
use actix_service::{ use actix_service::{
map_config, IntoService, IntoServiceFactory, Service, ServiceFactory, map_config, IntoService, IntoServiceFactory, Service, ServiceFactory,
}; };
@@ -30,7 +29,7 @@ pub use actix_http::test::TestBuffer;
use crate::config::AppConfig; use crate::config::AppConfig;
use crate::data::Data; use crate::data::Data;
use crate::dev::{Body, MessageBody, Payload}; use crate::dev::{Body, MessageBody, Payload, Server};
use crate::request::HttpRequestPool; use crate::request::HttpRequestPool;
use crate::rmap::ResourceMap; use crate::rmap::ResourceMap;
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::{ServiceRequest, ServiceResponse};
@@ -66,7 +65,7 @@ pub fn default_service(
/// let mut app = test::init_service( /// let mut app = test::init_service(
/// App::new() /// App::new()
/// .service(web::resource("/test").to(|| async { HttpResponse::Ok() })) /// .service(web::resource("/test").to(|| async { HttpResponse::Ok() }))
/// ); /// ).await;
/// ///
/// // Create request object /// // Create request object
/// let req = test::TestRequest::with_uri("/test").to_request(); /// let req = test::TestRequest::with_uri("/test").to_request();
@@ -627,14 +626,14 @@ where
let ctimeout = cfg.client_timeout; let ctimeout = cfg.client_timeout;
let builder = Server::build().workers(1).disable_signals(); let builder = Server::build().workers(1).disable_signals();
match cfg.stream { let srv = match cfg.stream {
StreamType::Tcp => match cfg.tp { StreamType::Tcp => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || { HttpVer::Http1 => builder.listen("test", tcp, move || {
let cfg = let cfg =
AppConfig::new(false, local_addr, format!("{}", local_addr)); AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.h1(map_config(factory().into_factory(), move |_| cfg.clone())) .h1(map_config(factory(), move |_| cfg.clone()))
.tcp() .tcp()
}), }),
HttpVer::Http2 => builder.listen("test", tcp, move || { HttpVer::Http2 => builder.listen("test", tcp, move || {
@@ -642,7 +641,7 @@ where
AppConfig::new(false, local_addr, format!("{}", local_addr)); AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.h2(map_config(factory().into_factory(), move |_| cfg.clone())) .h2(map_config(factory(), move |_| cfg.clone()))
.tcp() .tcp()
}), }),
HttpVer::Both => builder.listen("test", tcp, move || { HttpVer::Both => builder.listen("test", tcp, move || {
@@ -650,9 +649,7 @@ where
AppConfig::new(false, local_addr, format!("{}", local_addr)); AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.finish(map_config(factory().into_factory(), move |_| { .finish(map_config(factory(), move |_| cfg.clone()))
cfg.clone()
}))
.tcp() .tcp()
}), }),
}, },
@@ -663,7 +660,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr)); AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.h1(map_config(factory().into_factory(), move |_| cfg.clone())) .h1(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone()) .openssl(acceptor.clone())
}), }),
HttpVer::Http2 => builder.listen("test", tcp, move || { HttpVer::Http2 => builder.listen("test", tcp, move || {
@@ -671,7 +668,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr)); AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.h2(map_config(factory().into_factory(), move |_| cfg.clone())) .h2(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone()) .openssl(acceptor.clone())
}), }),
HttpVer::Both => builder.listen("test", tcp, move || { HttpVer::Both => builder.listen("test", tcp, move || {
@@ -679,9 +676,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr)); AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.finish(map_config(factory().into_factory(), move |_| { .finish(map_config(factory(), move |_| cfg.clone()))
cfg.clone()
}))
.openssl(acceptor.clone()) .openssl(acceptor.clone())
}), }),
}, },
@@ -692,7 +687,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr)); AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.h1(map_config(factory().into_factory(), move |_| cfg.clone())) .h1(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone()) .rustls(config.clone())
}), }),
HttpVer::Http2 => builder.listen("test", tcp, move || { HttpVer::Http2 => builder.listen("test", tcp, move || {
@@ -700,7 +695,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr)); AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.h2(map_config(factory().into_factory(), move |_| cfg.clone())) .h2(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone()) .rustls(config.clone())
}), }),
HttpVer::Both => builder.listen("test", tcp, move || { HttpVer::Both => builder.listen("test", tcp, move || {
@@ -708,9 +703,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr)); AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build() HttpService::build()
.client_timeout(ctimeout) .client_timeout(ctimeout)
.finish(map_config(factory().into_factory(), move |_| { .finish(map_config(factory(), move |_| cfg.clone()))
cfg.clone()
}))
.rustls(config.clone()) .rustls(config.clone())
}), }),
}, },
@@ -718,11 +711,11 @@ where
.unwrap() .unwrap()
.start(); .start();
tx.send((System::current(), local_addr)).unwrap(); tx.send((System::current(), srv, local_addr)).unwrap();
sys.run() sys.run()
}); });
let (system, addr) = rx.recv().unwrap(); let (system, server, addr) = rx.recv().unwrap();
let client = { let client = {
let connector = { let connector = {
@@ -737,7 +730,7 @@ where
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e)); .map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
Connector::new() Connector::new()
.conn_lifetime(time::Duration::from_secs(0)) .conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000)) .timeout(time::Duration::from_millis(30000))
.ssl(builder.build()) .ssl(builder.build())
.finish() .finish()
} }
@@ -745,7 +738,7 @@ where
{ {
Connector::new() Connector::new()
.conn_lifetime(time::Duration::from_secs(0)) .conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000)) .timeout(time::Duration::from_millis(30000))
.finish() .finish()
} }
}; };
@@ -758,6 +751,7 @@ where
addr, addr,
client, client,
system, system,
server,
} }
} }
@@ -854,6 +848,7 @@ pub struct TestServer {
client: awc::Client, client: awc::Client,
system: actix_rt::System, system: actix_rt::System,
ssl: bool, ssl: bool,
server: Server,
} }
impl TestServer { impl TestServer {
@@ -942,15 +937,17 @@ impl TestServer {
self.ws_at("/").await self.ws_at("/").await
} }
/// Stop http server /// Gracefully stop http server
fn stop(&mut self) { pub async fn stop(self) {
self.server.stop(true).await;
self.system.stop(); self.system.stop();
delay_for(time::Duration::from_millis(100)).await;
} }
} }
impl Drop for TestServer { impl Drop for TestServer {
fn drop(&mut self) { fn drop(&mut self) {
self.stop() self.system.stop()
} }
} }
@@ -962,7 +959,7 @@ mod tests {
use std::time::SystemTime; use std::time::SystemTime;
use super::*; use super::*;
use crate::{http::header, web, App, HttpResponse}; use crate::{http::header, web, App, HttpResponse, Responder};
#[actix_rt::test] #[actix_rt::test]
async fn test_basics() { async fn test_basics() {
@@ -1148,6 +1145,25 @@ mod tests {
assert!(res.status().is_success()); assert!(res.status().is_success());
} }
#[actix_rt::test]
async fn test_server_data() {
async fn handler(data: web::Data<usize>) -> impl Responder {
assert_eq!(**data, 10);
HttpResponse::Ok()
}
let mut app = init_service(
App::new()
.data(10usize)
.service(web::resource("/index.html").to(handler)),
)
.await;
let req = TestRequest::post().uri("/index.html").to_request();
let res = app.call(req).await.unwrap();
assert!(res.status().is_success());
}
#[actix_rt::test] #[actix_rt::test]
async fn test_actor() { async fn test_actor() {
use actix::Actor; use actix::Actor;

View File

@@ -365,7 +365,7 @@ where
.map_err(|_| UrlencodedError::Parse) .map_err(|_| UrlencodedError::Parse)
} }
} }
.boxed_local(), .boxed_local(),
); );
self.poll(cx) self.poll(cx)
} }

View File

@@ -396,7 +396,7 @@ where
} }
Ok(serde_json::from_slice::<U>(&body)?) Ok(serde_json::from_slice::<U>(&body)?)
} }
.boxed_local(), .boxed_local(),
); );
self.poll(cx) self.poll(cx)

View File

@@ -229,7 +229,7 @@ impl FromRequest for String {
.ok_or_else(|| ErrorBadRequest("Can not decode body"))?) .ok_or_else(|| ErrorBadRequest("Can not decode body"))?)
} }
} }
.boxed_local(), .boxed_local(),
) )
} }
} }
@@ -391,7 +391,7 @@ impl Future for HttpMessageBody {
} }
Ok(body.freeze()) Ok(body.freeze())
} }
.boxed_local(), .boxed_local(),
); );
self.poll(cx) self.poll(cx)
} }

View File

@@ -1,5 +1,6 @@
//! Essentials helper functions and types for application registration. //! Essentials helper functions and types for application registration.
use actix_http::http::Method; use actix_http::http::Method;
use actix_router::IntoPattern;
use futures::Future; use futures::Future;
pub use actix_http::Response as HttpResponse; pub use actix_http::Response as HttpResponse;
@@ -50,7 +51,7 @@ pub use crate::types::*;
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// ); /// );
/// ``` /// ```
pub fn resource(path: &str) -> Resource { pub fn resource<T: IntoPattern>(path: T) -> Resource {
Resource::new(path) Resource::new(path)
} }
@@ -249,7 +250,7 @@ where
/// .finish(my_service) /// .finish(my_service)
/// ); /// );
/// ``` /// ```
pub fn service(path: &str) -> WebService { pub fn service<T: IntoPattern>(path: T) -> WebService {
WebService::new(path) WebService::new(path)
} }

View File

@@ -30,7 +30,7 @@ default = []
openssl = ["open-ssl", "awc/openssl"] openssl = ["open-ssl", "awc/openssl"]
[dependencies] [dependencies]
actix-service = "1.0.0" actix-service = "1.0.1"
actix-codec = "0.2.0" actix-codec = "0.2.0"
actix-connect = "1.0.0" actix-connect = "1.0.0"
actix-utils = "1.0.3" actix-utils = "1.0.3"

View File

@@ -77,7 +77,7 @@ pub fn test_server<F: ServiceFactory<TcpStream>>(factory: F) -> TestServer {
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e)); .map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
Connector::new() Connector::new()
.conn_lifetime(time::Duration::from_secs(0)) .conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000)) .timeout(time::Duration::from_millis(30000))
.ssl(builder.build()) .ssl(builder.build())
.finish() .finish()
} }
@@ -85,7 +85,7 @@ pub fn test_server<F: ServiceFactory<TcpStream>>(factory: F) -> TestServer {
{ {
Connector::new() Connector::new()
.conn_lifetime(time::Duration::from_secs(0)) .conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000)) .timeout(time::Duration::from_millis(30000))
.finish() .finish()
} }
}; };

View File

@@ -42,7 +42,7 @@ async fn test_start() {
.disable_signals() .disable_signals()
.bind(format!("{}", addr)) .bind(format!("{}", addr))
.unwrap() .unwrap()
.start(); .run();
let _ = tx.send((srv, actix_rt::System::current())); let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run(); let _ = sys.run();
@@ -111,7 +111,7 @@ async fn test_start_ssl() {
.disable_signals() .disable_signals()
.bind_openssl(format!("{}", addr), builder) .bind_openssl(format!("{}", addr), builder)
.unwrap() .unwrap()
.start(); .run();
let _ = tx.send((srv, actix_rt::System::current())); let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run(); let _ = sys.run();