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

Compare commits

...

56 Commits

Author SHA1 Message Date
d92d53a4f5 Merge pull request #1541 from JohnTitor/backport-files
files: Bump up to 0.2.2
2020-05-27 00:37:29 +09:00
55d79cc1b2 files: Bump up to 0.2.2 2020-05-26 17:22:16 +09:00
a8117183bb files: Minimize futures dependencies 2020-05-26 17:19:12 +09:00
60dcfd1aff Actix-files will always send SizedStream (#1496)
* Fixes #1384

* There is no need to set no_chunking

* Test content-length for static files

* Update the tests

* Add Changelog

* Try to simply fix Windows test issues!

Co-authored-by: Rob Ede <robjtede@icloud.com>
2020-05-26 17:18:47 +09:00
7870165da2 Fix spelling error 2020-05-26 17:14:33 +09:00
6560a2285f Suppress warning 2020-05-26 17:13:35 +09:00
12eccf40e1 Merge pull request #1539 from JohnTitor/framed-0.3.1
framed: Bump up to 0.3.1 with deprecation notice
2020-05-25 18:58:32 +09:00
7a9c0f632d framed: Bump up to 0.3.1 with deprecation notice 2020-05-25 18:20:55 +09:00
7baa35a897 Merge pull request #1526 from actix/backport-gha
2.0: Tweak CI config
2020-05-21 15:04:28 +09:00
ea0d748a5e Remove Travis and AppVeyor config 2020-05-21 12:07:54 +09:00
bc4f98321a 2.0: Tweak GHA config 2020-05-21 12:06:05 +09:00
2ddbe2b15c Merge pull request #1400 from JohnTitor/actions-2.0
[2.0 backport] Tweaks for GitHub Actions
2020-03-08 03:04:31 +09:00
87378a7410 Demote lint level to warn 2020-03-08 02:23:55 +09:00
ad0d809af6 Disable coverage for PRs 2020-03-08 02:03:08 +09:00
7b00c16d44 Add some Actions workflows 2020-03-08 02:02:52 +09:00
155a6db4cd More ignore test causes timeout 2020-03-08 02:02:15 +09:00
228e886986 Don't use cache in Windows CI (#1327) 2020-03-08 02:01:59 +09:00
4aa4b5f928 Tweak caches (#1319)
* Try to use `cargo-cache`

* Tweak issue template
2020-03-08 02:01:45 +09:00
54ff97470e Initial Issue template (#1311)
* Initial Issue template

* First round of changes for the bug report

Co-authored-by: Yuki Okushi <huyuumi.dev@gmail.com>
2020-03-08 02:01:31 +09:00
f02ad2913f Fix vcpkg cache (#1312) 2020-03-08 02:01:17 +09:00
96b0dfeac3 Tweak actions (#1305)
* Add benchmark action

* Fix Windows build
2020-03-08 02:00:58 +09:00
3a5b62b550 Add dependencies instruction (#1281) 2020-01-16 23:17:17 +09:00
412e54ce10 Fixed documentation typo for actix-files (#1278) 2020-01-15 11:09:58 -08:00
bca41f8d40 Changes to Cors builder (#1266)
Co-authored-by: Yuki Okushi <huyuumi.dev@gmail.com>
2020-01-11 04:53:17 +09:00
7c974ee668 Update doc comment for HttpRequest::app_data (#1265)
* update doc comment for `HttpRequest::app_data`

* add `no_run` to doc comment

* add `ignore` to doc comment

* Update src/request.rs

Co-Authored-By: Yuki Okushi <huyuumi.dev@gmail.com>

Co-authored-by: Yuki Okushi <huyuumi.dev@gmail.com>
2020-01-11 03:55:20 +09:00
abb462ef85 Replace sha1 dependency with sha-1 (#1258)
* Replace sha1 dependency with sha-1

This other crate is being maintained, and it offers better performances
when using the `asm` feature (especially [on
AArch64](https://github.com/RustCrypto/hashes/pull/97)).

* Update CHANGES.md with the sha-1 migration

* Add a test for hash_key()
2020-01-11 02:34:31 +09:00
e66312b664 add extra constraints 2020-01-10 11:36:59 +06:00
39f4b2b39e Merge branch 'master' of github.com:actix/actix-web 2020-01-10 11:28:58 +06:00
f6ff056b8a Fix panic with already borrowed: BorrowMutError #1263 2020-01-10 11:26:54 +06:00
51ab4fb73d Tweak actions to use cache and not to be stuck on the way (#1264) 2020-01-10 03:30:45 +09:00
f5fd6bc49f Fix actix-http examples (#1259)
Fix actix-http examples
2020-01-07 00:15:04 +09:00
2803fcbe22 Small grammaritical update to lib.rs (#1248) 2020-01-03 08:45:17 +06:00
67793c5d92 add ssl feature migration 2019-12-30 21:22:04 +06:00
bcb5086c91 Added 2.0.0 rustls feature name change (#1244) 2019-12-30 21:16:04 +06:00
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
a4ad5e6b69 update timeouts for test server 2019-12-25 20:52:20 +04:00
6db909a3e7 update migration 2019-12-25 20:27:30 +04:00
642ae161c0 prep actix-web release 2019-12-25 20:21:00 +04:00
7b3c99b933 prep actix-framed release 2019-12-25 20:17:22 +04:00
f86ce0390e allow to specify multi pattern for resources 2019-12-25 20:14:44 +04:00
7882f545e5 Allow to gracefully stop test server via TestServer::stop() 2019-12-25 12:10:48 +04:00
1c75e6876b update migration 2019-12-22 17:16:07 +04:00
6a0cd2dced Rename HttpServer::start() to HttpServer::run() 2019-12-22 17:12:22 +04:00
c7f3915779 update actix-service dep 2019-12-22 16:39:25 +04:00
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
3751a4018e fixed test::init_service api docs (missing await) (#1230) 2019-12-21 08:47:18 +06:00
0cb1b0642f add test server data test 2019-12-20 23:18:59 +06:00
48476362a3 update changes 2019-12-20 17:59:34 +06:00
2b4256baab add links to configs 2019-12-20 17:49:05 +06:00
e5a50f423d Make web::Data deref to Arc<T> #1214 2019-12-20 17:45:35 +06:00
8b8a9a995d bump ver 2019-12-20 17:36:48 +06:00
74fa4060c2 fix awc tests 2019-12-20 17:27:32 +06:00
c877840c07 rename App::register_data to App::app_data and HttpRequest::app_data returns Option<&T> instead of Option<&Data<T>> 2019-12-20 17:13:09 +06:00
20248daeda Allow to set peer_addr for TestRequest #1074 2019-12-20 16:11:51 +06:00
a08d8dab70 AppConfig::secure() is always false. #1202 2019-12-20 16:04:51 +06:00
fbbb4a86e9 feat: add access to the session also from immutable references (#1225) 2019-12-20 13:59:07 +06:00
76 changed files with 998 additions and 577 deletions

View File

@ -1,41 +0,0 @@
environment:
global:
PROJECT_NAME: actix-web
matrix:
# Stable channel
- TARGET: i686-pc-windows-msvc
CHANNEL: stable
- TARGET: x86_64-pc-windows-gnu
CHANNEL: stable
- TARGET: x86_64-pc-windows-msvc
CHANNEL: stable
# Nightly channel
- TARGET: i686-pc-windows-msvc
CHANNEL: nightly
- TARGET: x86_64-pc-windows-gnu
CHANNEL: nightly
- TARGET: x86_64-pc-windows-msvc
CHANNEL: nightly
# Install Rust and Cargo
# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml)
install:
- ps: >-
If ($Env:TARGET -eq 'x86_64-pc-windows-gnu') {
$Env:PATH += ';C:\msys64\mingw64\bin'
} ElseIf ($Env:TARGET -eq 'i686-pc-windows-gnu') {
$Env:PATH += ';C:\MinGW\bin'
}
- curl -sSf -o rustup-init.exe https://win.rustup.rs
- rustup-init.exe --default-host %TARGET% --default-toolchain %CHANNEL% -y
- set PATH=%PATH%;C:\Users\appveyor\.cargo\bin
- rustc -Vv
- cargo -V
# 'cargo test' takes care of building for us, so disable Appveyor's build stage.
build: false
# Equivalent to Travis' `script` phase
test_script:
- cargo clean
- cargo test --no-default-features --features="flate2-rust"

37
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,37 @@
---
name: bug report
about: create a bug report
---
Your issue may already be reported!
Please search on the [Actix Web issue tracker](https://github.com/actix/actix-web/issues) before creating one.
## Expected Behavior
<!--- If you're describing a bug, tell us what should happen -->
<!--- If you're suggesting a change/improvement, tell us how it should work -->
## Current Behavior
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
## Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
<!--- or ideas how to implement the addition or change -->
## Steps to Reproduce (for bugs)
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
<!--- reproduce this bug. Include code to reproduce, if relevant -->
1.
2.
3.
4.
## Context
<!--- How has this issue affected you? What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world -->
## Your Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
* Rust Version (I.e, output of `rustc -V`):
* Actix Web Version:

53
.github/workflows/linux.yml vendored Normal file
View File

@ -0,0 +1,53 @@
name: CI (Linux)
on: [push, pull_request]
jobs:
build_and_test:
strategy:
fail-fast: false
matrix:
version:
- 1.39.0 # MSRV
- stable
- nightly
name: ${{ matrix.version }} - x86_64-unknown-linux-gnu
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Install ${{ matrix.version }}
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.version }}-x86_64-unknown-linux-gnu
profile: minimal
override: true
- name: check build
uses: actions-rs/cargo@v1
with:
command: check
args: --all --bins --examples --tests
- name: tests
uses: actions-rs/cargo@v1
timeout-minutes: 40
with:
command: test
args: --all --all-features --no-fail-fast -- --nocapture
- name: tests (actix-http)
uses: actions-rs/cargo@v1
timeout-minutes: 40
with:
command: test
args: --package=actix-http --no-default-features --features=rustls -- --nocapture
- name: tests (awc)
uses: actions-rs/cargo@v1
timeout-minutes: 40
with:
command: test
args: --package=awc --no-default-features --features=rustls -- --nocapture

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

@ -0,0 +1,39 @@
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: 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

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

@ -0,0 +1,58 @@
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: Install OpenSSL
run: |
vcpkg integrate install
vcpkg install openssl:x64-windows
Copy-Item C:\vcpkg\installed\x64-windows\bin\libcrypto-1_1-x64.dll C:\vcpkg\installed\x64-windows\bin\libcrypto.dll
Copy-Item C:\vcpkg\installed\x64-windows\bin\libssl-1_1-x64.dll C:\vcpkg\installed\x64-windows\bin\libssl.dll
Get-ChildItem C:\vcpkg\installed\x64-windows\bin
Get-ChildItem C:\vcpkg\installed\x64-windows\lib
- 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
--skip=test_connection_force_close
--skip=test_connection_server_close
--skip=test_connection_wait_queue_force_close

View File

@ -1,61 +0,0 @@
language: rust
sudo: required
dist: trusty
cache:
# cargo: true
apt: true
matrix:
include:
- rust: stable
- rust: beta
- rust: nightly-2019-11-20
allow_failures:
- rust: nightly-2019-11-20
env:
global:
# - RUSTFLAGS="-C link-dead-code"
- OPENSSL_VERSION=openssl-1.0.2
before_install:
- sudo add-apt-repository -y ppa:0k53d-karl-f830m/openssl
- sudo apt-get update -qq
- sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev
before_cache: |
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-11-20" ]]; then
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
fi
# Add clippy
before_script:
- export PATH=$PATH:~/.cargo/bin
script:
- cargo update
- cargo check --all --no-default-features
- |
if [[ "$TRAVIS_RUST_VERSION" == "stable" || "$TRAVIS_RUST_VERSION" == "beta" ]]; then
cargo test --all-features --all -- --nocapture
cd actix-http; cargo test --no-default-features --features="rustls" -- --nocapture; cd ..
cd awc; cargo test --no-default-features --features="rustls" -- --nocapture; cd ..
fi
# Upload docs
after_success:
- |
if [[ "$TRAVIS_OS_NAME" == "linux" && "$TRAVIS_PULL_REQUEST" = "false" && "$TRAVIS_BRANCH" == "master" && "$TRAVIS_RUST_VERSION" == "stable" ]]; then
cargo doc --no-deps --all-features &&
echo "<meta http-equiv=refresh content=0;url=os_balloon/index.html>" > target/doc/index.html &&
git clone https://github.com/davisp/ghp-import.git &&
./ghp-import/ghp_import.py -n -p -f -m "Documentation upload" -r https://"$GH_TOKEN"@github.com/"$TRAVIS_REPO_SLUG.git" target/doc &&
echo "Uploaded documentation"
fi
- |
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-11-20" ]]; then
taskset -c 0 cargo tarpaulin --out Xml --all --all-features
bash <(curl -s https://codecov.io/bash)
echo "Uploaded code coverage"
fi

View File

@ -1,11 +1,40 @@
# Changes
## [2.0.0] - 2019-12-xx
## [2.0.NEXT] - 2020-01-xx
### Changed
* Use `sha-1` crate instead of unmaintained `sha1` crate
## [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
### Changed
* Move `BodyEncoding` to `dev` module #1220
* Allow to set `peer_addr` for TestRequest #1074
* Make web::Data deref to Arc<T> #1214
* Rename `App::register_data()` to `App::app_data()`
* `HttpRequest::app_data<T>()` returns `Option<&T>` instead of `Option<&Data<T>>`
### Fixed
* Fix `AppConfig::secure()` is always false. #1202
## [2.0.0-alpha.6] - 2019-12-15
### Fixed

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web"
version = "2.0.0-alpha.6"
version = "2.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
readme = "README.md"
@ -60,18 +60,18 @@ rustls = ["actix-tls/rustls", "awc/rustls", "rust-tls"]
[dependencies]
actix-codec = "0.2.0"
actix-service = "1.0.0"
actix-utils = "1.0.3"
actix-router = "0.2.0"
actix-service = "1.0.2"
actix-utils = "1.0.6"
actix-router = "0.2.4"
actix-rt = "1.0.0"
actix-server = "1.0.0"
actix-testing = "1.0.0"
actix-macros = "0.1.0"
actix-threadpool = "0.3.0"
actix-threadpool = "0.3.1"
actix-tls = "1.0.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 }
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 }
[dev-dependencies]
actix = "0.9.0-alpha.2"
actix = "0.9.0"
rand = "0.7"
env_logger = "0.6"
serde_derive = "1.0"

View File

@ -1,11 +1,50 @@
## 2.0.0
* Sync handlers has been removed. `.to_async()` method has been renamed to `.to()`
* `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`.
Stored data is available via `HttpRequest::app_data()` method at runtime.
* 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()`
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"] }
```
* `Cors` builder now requires that you call `.finish()` to construct the middleware
## 1.0.1

View File

@ -41,6 +41,16 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
## Example
Dependencies:
```toml
[dependencies]
actix-web = "2"
actix-rt = "1"
```
Code:
```rust
use actix_web::{get, web, App, HttpServer, Responder};
@ -53,7 +63,7 @@ async fn index(info: web::Path<(u32, String)>) -> impl Responder {
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index))
.bind("127.0.0.1:8080")?
.start()
.run()
.await
}
```
@ -65,10 +75,11 @@ async fn main() -> std::io::Result<()> {
* [Multipart streams](https://github.com/actix/examples/tree/master/multipart/)
* [Simple websocket](https://github.com/actix/examples/tree/master/websocket/)
* [Tera](https://github.com/actix/examples/tree/master/template_tera/) /
[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/)
* [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/)
* [Json](https://github.com/actix/examples/tree/master/json/)

View File

@ -1,5 +1,9 @@
# Changes
## [0.2.0] - 2019-12-20
* Release
## [0.2.0-alpha.3] - 2019-12-07
* Migrate to actix-web 2.0.0

View File

@ -17,8 +17,8 @@ name = "actix_cors"
path = "src/lib.rs"
[dependencies]
actix-web = "2.0.0-alpha.5"
actix-service = "1.0.0"
actix-web = "2.0.0-rc"
actix-service = "1.0.1"
derive_more = "0.99.2"
futures = "0.3.1"

View File

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

View File

@ -1,6 +1,18 @@
# Changes
## [0.2.0] - 2019-12-xx
## [0.2.2] - 2020-05-26
* Minimize `futures` dependency
* Support sending Content-Length when Content-Range is specified [#1496]
* Update `actix-web` to 2.0.0
[#1496]: https://github.com/actix/actix-web/issues/1496
## [0.2.1] - 2019-12-22
* Use the same format for file URLs regardless of platforms
## [0.2.0] - 2019-12-20
* Fix BodyEncoding trait import #1220

View File

@ -1,6 +1,6 @@
[package]
name = "actix-files"
version = "0.2.0"
version = "0.2.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Static files support for actix web."
readme = "README.md"
@ -18,12 +18,13 @@ name = "actix_files"
path = "src/lib.rs"
[dependencies]
actix-web = { version = "2.0.0-alpha.6", default-features = false }
actix-http = "1.0.0"
actix-service = "1.0.0"
actix-web = { version = "2.0.0", default-features = false }
actix-http = "1.0.1"
actix-service = "1.0.1"
bitflags = "1"
bytes = "0.5.3"
futures = "0.3.1"
futures-core = { version = "0.3.5", default-features = false }
futures-util = { version = "0.3.5", default-features = false }
derive_more = "0.99.2"
log = "0.4"
mime = "0.3"
@ -33,4 +34,4 @@ v_htmlescape = "0.4"
[dev-dependencies]
actix-rt = "1.0.0"
actix-web = { version = "2.0.0-alpha.6", features=["openssl"] }
actix-web = { version = "2.0.0", features = ["openssl"] }

View File

@ -5,6 +5,7 @@ use derive_more::Display;
#[derive(Display, Debug, PartialEq)]
pub enum FilesError {
/// Path is not a directory
#[allow(dead_code)]
#[display(fmt = "Path is not a directory. Unable to serve static files")]
IsNotDirectory,

View File

@ -24,8 +24,8 @@ use actix_web::http::header::{self, DispositionType};
use actix_web::http::Method;
use actix_web::{web, FromRequest, HttpRequest, HttpResponse};
use bytes::Bytes;
use futures::future::{ok, ready, Either, FutureExt, LocalBoxFuture, Ready};
use futures::Stream;
use futures_core::Stream;
use futures_util::future::{ok, ready, Either, FutureExt, LocalBoxFuture, Ready};
use mime;
use mime_guess::from_ext;
use percent_encoding::{utf8_percent_encode, CONTROLS};
@ -155,7 +155,7 @@ impl Directory {
// show file url as relative to static path
macro_rules! encode_file_url {
($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) {
let entry = entry.unwrap();
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,
};
@ -272,7 +275,7 @@ impl Files {
///
/// `File` uses `ThreadPool` for blocking filesystem operations.
/// By default pool with 5x threads of available cpus is used.
/// Pool size can be changed by setting ACTIX_CPU_POOL environment variable.
/// Pool size can be changed by setting ACTIX_THREADPOOL environment variable.
pub fn new<T: Into<PathBuf>>(path: &str, dir: T) -> Files {
let orig_dir = dir.into();
let dir = match orig_dir.canonicalize() {
@ -518,7 +521,7 @@ impl Service for FilesService {
Err(e) => return Either::Left(ok(req.error_response(e))),
};
// full filepath
// full file path
let path = match self.directory.join(&real_path.0).canonicalize() {
Ok(path) => path,
Err(e) => return self.handle_err(e, req),
@ -949,135 +952,92 @@ mod tests {
#[actix_rt::test]
async fn test_named_file_content_range_headers() {
let mut srv = test::init_service(
App::new().service(Files::new("/test", ".").index_file("tests/test.binary")),
)
.await;
let srv = test::start(|| {
App::new().service(Files::new("/", "."))
});
// Valid range header
let request = TestRequest::get()
.uri("/t%65st/tests/test.binary")
let response = srv
.get("/tests/test.binary")
.header(header::RANGE, "bytes=10-20")
.to_request();
let response = test::call_service(&mut srv, request).await;
let contentrange = response
.headers()
.get(header::CONTENT_RANGE)
.unwrap()
.to_str()
.send()
.await
.unwrap();
assert_eq!(contentrange, "bytes 10-20/100");
let content_range = response.headers().get(header::CONTENT_RANGE).unwrap();
assert_eq!(content_range.to_str().unwrap(), "bytes 10-20/100");
// Invalid range header
let request = TestRequest::get()
.uri("/t%65st/tests/test.binary")
let response = srv
.get("/tests/test.binary")
.header(header::RANGE, "bytes=10-5")
.to_request();
let response = test::call_service(&mut srv, request).await;
let contentrange = response
.headers()
.get(header::CONTENT_RANGE)
.unwrap()
.to_str()
.send()
.await
.unwrap();
assert_eq!(contentrange, "bytes */100");
let content_range = response.headers().get(header::CONTENT_RANGE).unwrap();
assert_eq!(content_range.to_str().unwrap(), "bytes */100");
}
#[actix_rt::test]
async fn test_named_file_content_length_headers() {
// use actix_web::body::{MessageBody, ResponseBody};
let mut srv = test::init_service(
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
)
.await;
let srv = test::start(|| {
App::new().service(Files::new("/", "."))
});
// Valid range header
let request = TestRequest::get()
.uri("/t%65st/tests/test.binary")
let response = srv
.get("/tests/test.binary")
.header(header::RANGE, "bytes=10-20")
.to_request();
let _response = test::call_service(&mut srv, request).await;
.send()
.await
.unwrap();
let content_length = response.headers().get(header::CONTENT_LENGTH).unwrap();
assert_eq!(content_length.to_str().unwrap(), "11");
// let contentlength = response
// .headers()
// .get(header::CONTENT_LENGTH)
// .unwrap()
// .to_str()
// .unwrap();
// assert_eq!(contentlength, "11");
// Invalid range header
let request = TestRequest::get()
.uri("/t%65st/tests/test.binary")
.header(header::RANGE, "bytes=10-8")
.to_request();
let response = test::call_service(&mut srv, request).await;
assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
// Valid range header, starting from 0
let response = srv
.get("/tests/test.binary")
.header(header::RANGE, "bytes=0-20")
.send()
.await
.unwrap();
let content_length = response.headers().get(header::CONTENT_LENGTH).unwrap();
assert_eq!(content_length.to_str().unwrap(), "21");
// Without range header
let request = TestRequest::get()
.uri("/t%65st/tests/test.binary")
// .no_default_headers()
.to_request();
let _response = test::call_service(&mut srv, request).await;
let mut response = srv.get("/tests/test.binary").send().await.unwrap();
let content_length = response.headers().get(header::CONTENT_LENGTH).unwrap();
assert_eq!(content_length.to_str().unwrap(), "100");
// let contentlength = response
// .headers()
// .get(header::CONTENT_LENGTH)
// .unwrap()
// .to_str()
// .unwrap();
// assert_eq!(contentlength, "100");
// Should be no transfer-encoding
let transfer_encoding = response.headers().get(header::TRANSFER_ENCODING);
assert!(transfer_encoding.is_none());
// chunked
let request = TestRequest::get()
.uri("/t%65st/tests/test.binary")
.to_request();
let response = test::call_service(&mut srv, request).await;
// with enabled compression
// {
// let te = response
// .headers()
// .get(header::TRANSFER_ENCODING)
// .unwrap()
// .to_str()
// .unwrap();
// assert_eq!(te, "chunked");
// }
let bytes = test::read_body(response).await;
// Check file contents
let bytes = response.body().await.unwrap();
let data = Bytes::from(fs::read("tests/test.binary").unwrap());
assert_eq!(bytes, data);
}
#[actix_rt::test]
async fn test_head_content_length_headers() {
let mut srv = test::init_service(
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
)
.await;
let srv = test::start(|| {
App::new().service(Files::new("/", "."))
});
// Valid range header
let request = TestRequest::default()
.method(Method::HEAD)
.uri("/t%65st/tests/test.binary")
.to_request();
let _response = test::call_service(&mut srv, request).await;
let response = srv
.head("/tests/test.binary")
.send()
.await
.unwrap();
// TODO: fix check
// let contentlength = response
// .headers()
// .get(header::CONTENT_LENGTH)
// .unwrap()
// .to_str()
// .unwrap();
// assert_eq!(contentlength, "100");
let content_length = response
.headers()
.get(header::CONTENT_LENGTH)
.unwrap()
.to_str()
.unwrap();
assert_eq!(content_length, "100");
}
#[actix_rt::test]

View File

@ -18,7 +18,7 @@ use actix_web::http::header::{
};
use actix_web::http::{ContentEncoding, StatusCode};
use actix_web::{Error, HttpMessage, HttpRequest, HttpResponse, Responder};
use futures::future::{ready, Ready};
use futures_util::future::{ready, Ready};
use crate::range::HttpRange;
use crate::ChunkedReadFile;
@ -388,11 +388,12 @@ impl NamedFile {
fut: None,
counter: 0,
};
if offset != 0 || length != self.md.len() {
Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader))
} else {
Ok(resp.body(SizedStream::new(length, reader)))
resp.status(StatusCode::PARTIAL_CONTENT);
}
Ok(resp.body(SizedStream::new(length, reader)))
}
}

View File

@ -1,6 +1,6 @@
[package]
name = "actix-framed"
version = "0.3.0"
version = "0.3.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix framed app server"
readme = "README.md"
@ -13,7 +13,6 @@ categories = ["network-programming", "asynchronous",
"web-programming::websocket"]
license = "MIT/Apache-2.0"
edition = "2018"
workspace =".."
[lib]
name = "actix_framed"
@ -21,10 +20,10 @@ path = "src/lib.rs"
[dependencies]
actix-codec = "0.2.0"
actix-service = "1.0.0"
actix-router = "0.2.0"
actix-service = "1.0.1"
actix-router = "0.2.1"
actix-rt = "1.0.0"
actix-http = "1.0.0"
actix-http = "1.0.1"
bytes = "0.5.3"
futures = "0.3.1"

View File

@ -1,5 +1,7 @@
# Framed app for actix web [![Build Status](https://travis-ci.org/actix/actix-web.svg?branch=master)](https://travis-ci.org/actix/actix-web) [![codecov](https://codecov.io/gh/actix/actix-web/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-web) [![crates.io](https://meritbadge.herokuapp.com/actix-framed)](https://crates.io/crates/actix-framed) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
**Notice**: `actix-framed` is deprecated since we don't use it anymore.
## Documentation & community resources
* [API Documentation](https://docs.rs/actix-framed/)

View File

@ -1,5 +1,13 @@
# Changes
## [0.3.1] - 2020-05-25
* Deprecate this crate
## [0.3.0] - 2019-12-25
* Migrate to actix-http 1.0
## [0.2.1] - 2019-07-20
* Remove unneeded actix-utils dependency

View File

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

View File

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

View File

@ -40,7 +40,7 @@ failure = ["fail-ure"]
secure-cookies = ["ring"]
[dependencies]
actix-service = "1.0.0"
actix-service = "1.0.1"
actix-codec = "0.2.0"
actix-connect = "1.0.1"
actix-utils = "1.0.3"
@ -74,7 +74,7 @@ rand = "0.7"
regex = "1.3"
serde = "1.0"
serde_json = "1.0"
sha1 = "0.6"
sha-1 = "0.8"
slab = "0.4"
serde_urlencoded = "0.6.1"
time = "0.1.42"

View File

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

View File

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

View File

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

View File

@ -6,27 +6,21 @@ use actix_service::Service;
#[doc(hidden)]
/// Service that allows to turn non-clone service to a service with `Clone` impl
pub(crate) struct CloneableService<T>(Rc<UnsafeCell<T>>);
pub(crate) struct CloneableService<T: Service>(Rc<UnsafeCell<T>>);
impl<T> CloneableService<T> {
pub(crate) fn new(service: T) -> Self
where
T: Service,
{
impl<T: Service> CloneableService<T> {
pub(crate) fn new(service: T) -> Self {
Self(Rc::new(UnsafeCell::new(service)))
}
}
impl<T> Clone for CloneableService<T> {
impl<T: Service> Clone for CloneableService<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> Service for CloneableService<T>
where
T: Service,
{
impl<T: Service> Service for CloneableService<T> {
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;

View File

@ -47,7 +47,7 @@
//! ```
#![doc(html_root_url = "https://docs.rs/cookie/0.11")]
#![deny(missing_docs)]
#![warn(missing_docs)]
mod builder;
mod delta;

View File

@ -364,7 +364,7 @@ where
}
/// `Service` implementation for HTTP1 transport
pub struct H1ServiceHandler<T, S, B, X, U> {
pub struct H1ServiceHandler<T, S: Service, B, X: Service, U: Service> {
srv: CloneableService<S>,
expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>,

View File

@ -246,7 +246,7 @@ where
}
/// `Service` implementation for http/2 transport
pub struct H2ServiceHandler<T, S, B> {
pub struct H2ServiceHandler<T, S: Service, B> {
srv: CloneableService<S>,
cfg: ServiceConfig,
on_connect: Option<rc::Rc<dyn Fn(&T) -> Box<dyn DataFactory>>>,

View File

@ -1,5 +1,5 @@
//! Basic http primitives for actix-net framework.
#![deny(rust_2018_idioms, warnings)]
#![warn(rust_2018_idioms, warnings)]
#![allow(
clippy::type_complexity,
clippy::too_many_arguments,

View File

@ -443,7 +443,7 @@ where
}
/// `Service` implementation for http transport
pub struct HttpServiceHandler<T, S, B, X, U> {
pub struct HttpServiceHandler<T, S: Service, B, X: Service, U: Service> {
srv: CloneableService<S>,
expect: CloneableService<X>,
upgrade: Option<CloneableService<U>>,

View File

@ -207,12 +207,13 @@ static WS_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
// TODO: hash is always same size, we dont need String
pub fn hash_key(key: &[u8]) -> String {
use sha1::Digest;
let mut hasher = sha1::Sha1::new();
hasher.update(key);
hasher.update(WS_GUID.as_bytes());
hasher.input(key);
hasher.input(WS_GUID.as_bytes());
base64::encode(&hasher.digest().bytes())
base64::encode(hasher.result().as_ref())
}
#[cfg(test)]
@ -277,6 +278,12 @@ mod test {
assert_eq!(format!("{}", OpCode::Bad), "BAD");
}
#[test]
fn test_hash_key() {
let hash = hash_key(b"hello actix-web");
assert_eq!(&hash, "cR1dlyUUJKp0s/Bel25u5TgvC3E=");
}
#[test]
fn closecode_from_u16() {
assert_eq!(CloseCode::from(1000u16), CloseCode::Normal);

View File

@ -1,5 +1,13 @@
# Changes
## [0.2.1] - 2020-01-10
* Fix panic with already borrowed: BorrowMutError #1263
## [0.2.0] - 2019-12-20
* Use actix-web 2.0
## [0.1.0] - 2019-06-xx
* Move identity middleware to separate crate

View File

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

View File

@ -251,6 +251,15 @@ pub struct IdentityServiceMiddleware<S, T> {
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>
where
B: 'static,
@ -279,7 +288,9 @@ where
req.extensions_mut()
.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>();
if let Some(id) = id {
@ -294,7 +305,7 @@ where
Err(err) => Ok(req.error_response(err)),
}
}
.boxed_local()
.boxed_local()
}
}
@ -606,9 +617,10 @@ mod tests {
use std::borrow::Borrow;
use super::*;
use actix_service::into_service;
use actix_web::http::StatusCode;
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_NAME: &'static str = "actix_auth";
@ -1045,6 +1057,7 @@ mod tests {
assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
}
// https://github.com/actix/actix-web/issues/1263
#[actix_rt::test]
async fn test_identity_cookie_updated_on_visit_deadline() {
let mut srv = create_identity_server(|c| {
@ -1069,4 +1082,47 @@ mod tests {
);
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

@ -1,6 +1,10 @@
# Changes
## [2.0.0-alpha.4] - 2019-12-xx
## [0.2.0] - 2019-12-20
* Release
## [0.2.0-alpha.4] - 2019-12-xx
* Multipart handling now handles Pending during read of boundary #1205

View File

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

View File

@ -1,5 +1,13 @@
# Changes
## [0.3.0] - 2019-12-20
* Release
## [0.3.0-alpha.4] - 2019-12-xx
* Allow access to sessions also from not mutable references to the request
## [0.3.0-alpha.3] - 2019-12-xx
* Add access to the session from RequestHead for use of session from guard methods

View File

@ -22,8 +22,8 @@ default = ["cookie-session"]
cookie-session = ["actix-web/secure-cookies"]
[dependencies]
actix-web = "2.0.0-alpha.5"
actix-service = "1.0.0"
actix-web = "2.0.0-rc"
actix-service = "1.0.1"
bytes = "0.5.3"
derive_more = "0.99.2"
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())))
//! .bind("127.0.0.1:59880")?
//! .start()
//! .run()
//! .await
//! }
//! ```
@ -85,23 +85,23 @@ pub struct Session(Rc<RefCell<SessionInner>>);
/// Helper trait that allows to get session
pub trait UserSession {
fn get_session(&mut self) -> Session;
fn get_session(&self) -> Session;
}
impl UserSession for HttpRequest {
fn get_session(&mut self) -> Session {
fn get_session(&self) -> Session {
Session::get_session(&mut *self.extensions_mut())
}
}
impl UserSession for ServiceRequest {
fn get_session(&mut self) -> Session {
fn get_session(&self) -> Session {
Session::get_session(&mut *self.extensions_mut())
}
}
impl UserSession for RequestHead {
fn get_session(&mut self) -> Session {
fn get_session(&self) -> Session {
Session::get_session(&mut *self.extensions_mut())
}
}

View File

@ -1,5 +1,9 @@
# Changes
## [2.0.0] - 2019-12-20
* Release
## [2.0.0-alpha.1] - 2019-12-15
* Migrate to actix-web 2.0.0

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web-actors"
version = "2.0.0-alpha.1"
version = "2.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix actors support for actix web framework."
readme = "README.md"
@ -16,9 +16,9 @@ name = "actix_web_actors"
path = "src/lib.rs"
[dependencies]
actix = "0.9.0-alpha.1"
actix-web = "2.0.0-alpha.5"
actix-http = "1.0.0"
actix = "0.9.0"
actix-web = "2.0.0-rc"
actix-http = "1.0.1"
actix-codec = "0.2.0"
bytes = "0.5.2"
futures = "0.3.1"

View File

@ -18,5 +18,5 @@ proc-macro2 = "^1"
[dev-dependencies]
actix-rt = { version = "1.0.0" }
actix-web = { version = "2.0.0-alpha.4" }
actix-web = { version = "2.0.0-rc" }
futures = { version = "0.3.1" }

View File

@ -35,7 +35,7 @@ compress = ["actix-http/compress"]
[dependencies]
actix-codec = "0.2.0"
actix-service = "1.0.0"
actix-service = "1.0.1"
actix-http = "1.0.0"
actix-rt = "1.0.0"
@ -55,8 +55,8 @@ rust-tls = { version = "0.16.0", package="rustls", optional = true, features = [
[dev-dependencies]
actix-connect = { version = "1.0.1", features=["openssl"] }
actix-web = { version = "2.0.0-alpha.5", features=["openssl"] }
actix-http = { version = "1.0.0", features=["openssl"] }
actix-web = { version = "2.0.0-rc", features=["openssl"] }
actix-http = { version = "1.0.1", features=["openssl"] }
actix-http-test = { version = "1.0.0", features=["openssl"] }
actix-utils = "1.0.3"
actix-server = "1.0.0"

View File

@ -1,4 +1,4 @@
#![deny(rust_2018_idioms, warnings)]
#![warn(rust_2018_idioms, warnings)]
#![allow(
clippy::type_complexity,
clippy::borrow_interior_mutable_const,

View File

@ -14,8 +14,8 @@ use rand::Rng;
use actix_http::HttpService;
use actix_http_test::test_server;
use actix_service::pipeline_factory;
use actix_web::dev::BodyEncoding;
use actix_service::{map_config, pipeline_factory};
use actix_web::dev::{AppConfig, BodyEncoding};
use actix_web::http::Cookie;
use actix_web::middleware::Compress;
use actix_web::{
@ -170,10 +170,11 @@ async fn test_connection_reuse() {
ok(io)
})
.and_then(
HttpService::new(
HttpService::new(map_config(
App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
)
|_| AppConfig::default(),
))
.tcp(),
)
});
@ -206,10 +207,11 @@ async fn test_connection_force_close() {
ok(io)
})
.and_then(
HttpService::new(
HttpService::new(map_config(
App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))),
)
|_| AppConfig::default(),
))
.tcp(),
)
});
@ -242,12 +244,13 @@ async fn test_connection_server_close() {
ok(io)
})
.and_then(
HttpService::new(
HttpService::new(map_config(
App::new().service(
web::resource("/")
.route(web::to(|| HttpResponse::Ok().force_close().finish())),
),
)
|_| AppConfig::default(),
))
.tcp(),
)
});
@ -280,8 +283,11 @@ async fn test_connection_wait_queue() {
ok(io)
})
.and_then(
HttpService::new(App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
HttpService::new(map_config(
App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok().body(STR))),
),
|_| AppConfig::default(),
))
.tcp(),
)
@ -324,12 +330,13 @@ async fn test_connection_wait_queue_force_close() {
ok(io)
})
.and_then(
HttpService::new(
HttpService::new(map_config(
App::new().service(
web::resource("/")
.route(web::to(|| HttpResponse::Ok().force_close().body(STR))),
),
)
|_| AppConfig::default(),
))
.tcp(),
)
});

View File

@ -4,9 +4,9 @@ use std::sync::Arc;
use actix_http::HttpService;
use actix_http_test::test_server;
use actix_service::{pipeline_factory, ServiceFactory};
use actix_service::{map_config, pipeline_factory, ServiceFactory};
use actix_web::http::Version;
use actix_web::{web, App, HttpResponse};
use actix_web::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok;
use open_ssl::ssl::{SslAcceptor, SslFiletype, SslMethod, SslVerifyMode};
use rust_tls::ClientConfig;
@ -62,8 +62,12 @@ async fn _test_connection_reuse_h2() {
})
.and_then(
HttpService::build()
.h2(App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
.h2(map_config(
App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
),
|_| AppConfig::default(),
))
.openssl(ssl_acceptor())
.map_err(|_| ()),
)

View File

@ -4,9 +4,9 @@ use std::sync::Arc;
use actix_http::HttpService;
use actix_http_test::test_server;
use actix_service::{pipeline_factory, ServiceFactory};
use actix_service::{map_config, pipeline_factory, ServiceFactory};
use actix_web::http::Version;
use actix_web::{web, App, HttpResponse};
use actix_web::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok;
use open_ssl::ssl::{SslAcceptor, SslConnector, SslFiletype, SslMethod, SslVerifyMode};
@ -44,8 +44,12 @@ async fn test_connection_reuse_h2() {
})
.and_then(
HttpService::build()
.h2(App::new()
.service(web::resource("/").route(web::to(|| HttpResponse::Ok()))))
.h2(map_config(
App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
),
|_| AppConfig::default(),
))
.openssl(ssl_acceptor())
.map_err(|_| ()),
)

View File

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

View File

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

View File

@ -5,6 +5,7 @@ use std::marker::PhantomData;
use std::rc::Rc;
use actix_http::body::{Body, MessageBody};
use actix_http::Extensions;
use actix_service::boxed::{self, BoxServiceFactory};
use actix_service::{
apply, apply_fn_factory, IntoServiceFactory, ServiceFactory, Transform,
@ -12,7 +13,7 @@ use actix_service::{
use futures::future::{FutureExt, LocalBoxFuture};
use crate::app_service::{AppEntry, AppInit, AppRoutingFactory};
use crate::config::{AppConfig, AppConfigInner, ServiceConfig};
use crate::config::ServiceConfig;
use crate::data::{Data, DataFactory};
use crate::dev::ResourceDef;
use crate::error::Error;
@ -36,8 +37,8 @@ pub struct App<T, B> {
factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
data: Vec<Box<dyn DataFactory>>,
data_factories: Vec<FnDataFactory>,
config: AppConfigInner,
external: Vec<ResourceDef>,
extensions: Extensions,
_t: PhantomData<B>,
}
@ -52,8 +53,8 @@ impl App<AppEntry, Body> {
services: Vec::new(),
default: None,
factory_ref: fref,
config: AppConfigInner::default(),
external: Vec::new(),
extensions: Extensions::new(),
_t: PhantomData,
}
}
@ -77,8 +78,9 @@ where
/// an application instance. Http server constructs an application
/// instance for each thread, thus application data must be constructed
/// multiple times. If you want to share data between different
/// threads, a shared object should be used, e.g. `Arc`. Application
/// data does not need to be `Send` or `Sync`.
/// threads, a shared object should be used, e.g. `Arc`. Internally `Data` type
/// uses `Arc` so data could be created outside of app factory and clones could
/// be stored via `App::app_data()` method.
///
/// ```rust
/// use std::cell::Cell;
@ -135,10 +137,15 @@ where
self
}
/// Set application data. Application data could be accessed
/// by using `Data<T>` extractor where `T` is data type.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
self.data.push(Box::new(data));
/// Set application level arbitrary data item.
///
/// Application data stored with `App::app_data()` method is available
/// via `HttpRequest::app_data()` method at runtime.
///
/// This method could be used for storing `Data<T>` as well, in that case
/// data could be accessed by using `Data<T>` extractor.
pub fn app_data<U: 'static>(mut self, ext: U) -> Self {
self.extensions.insert(ext);
self
}
@ -225,18 +232,6 @@ where
self
}
/// Set server host name.
///
/// Host name is used by application router as a hostname for url generation.
/// Check [ConnectionInfo](./dev/struct.ConnectionInfo.html#method.host)
/// documentation for more information.
///
/// By default host name is set to a "localhost" value.
pub fn hostname(mut self, val: &str) -> Self {
self.config.host = val.to_owned();
self
}
/// Default service to be used if no matching resource could be found.
///
/// It is possible to use services like `Resource`, `Route`.
@ -383,8 +378,8 @@ where
services: self.services,
default: self.default,
factory_ref: self.factory_ref,
config: self.config,
external: self.external,
extensions: self.extensions,
_t: PhantomData,
}
}
@ -445,8 +440,8 @@ where
services: self.services,
default: self.default,
factory_ref: self.factory_ref,
config: self.config,
external: self.external,
extensions: self.extensions,
_t: PhantomData,
}
}
@ -472,7 +467,7 @@ where
external: RefCell::new(self.external),
default: self.default,
factory_ref: self.factory_ref,
config: RefCell::new(AppConfig(Rc::new(self.config))),
extensions: RefCell::new(Some(self.extensions)),
}
}
}
@ -556,6 +551,20 @@ mod tests {
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[actix_rt::test]
async fn test_extension() {
let mut srv = init_service(App::new().app_data(10usize).service(
web::resource("/").to(|req: HttpRequest| {
assert_eq!(*req.app_data::<usize>().unwrap(), 10);
HttpResponse::Ok()
}),
))
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn test_wrap() {
let mut srv = init_service(

View File

@ -39,9 +39,9 @@ where
>,
{
pub(crate) endpoint: T,
pub(crate) extensions: RefCell<Option<Extensions>>,
pub(crate) data: Rc<Vec<Box<dyn DataFactory>>>,
pub(crate) data_factories: Rc<Vec<FnDataFactory>>,
pub(crate) config: RefCell<AppConfig>,
pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>,
pub(crate) default: Option<Rc<HttpNewService>>,
pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>,
@ -58,7 +58,7 @@ where
InitError = (),
>,
{
type Config = ();
type Config = AppConfig;
type Request = Request;
type Response = ServiceResponse<B>;
type Error = T::Error;
@ -66,7 +66,7 @@ where
type Service = AppInitService<T::Service, B>;
type Future = AppInitResult<T, B>;
fn new_service(&self, _: ()) -> Self::Future {
fn new_service(&self, config: AppConfig) -> Self::Future {
// update resource default service
let default = self.default.clone().unwrap_or_else(|| {
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| {
@ -75,11 +75,7 @@ where
});
// App config
let mut config = AppService::new(
self.config.borrow().clone(),
default.clone(),
self.data.clone(),
);
let mut config = AppService::new(config, default.clone(), self.data.clone());
// register services
std::mem::replace(&mut *self.services.borrow_mut(), Vec::new())
@ -119,6 +115,12 @@ where
data: self.data.clone(),
data_factories: Vec::new(),
data_factories_fut: self.data_factories.iter().map(|f| f()).collect(),
extensions: Some(
self.extensions
.borrow_mut()
.take()
.unwrap_or_else(Extensions::new),
),
config,
rmap,
_t: PhantomData,
@ -139,6 +141,7 @@ where
data: Rc<Vec<Box<dyn DataFactory>>>,
data_factories: Vec<Box<dyn DataFactory>>,
data_factories_fut: Vec<LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>,
extensions: Option<Extensions>,
_t: PhantomData<B>,
}
@ -177,7 +180,7 @@ where
if this.endpoint.is_some() && this.data_factories_fut.is_empty() {
// create app data container
let mut data = Extensions::new();
let mut data = this.extensions.take().unwrap();
for f in this.data.iter() {
f.create(&mut data);
}

View File

@ -124,14 +124,20 @@ impl AppService {
}
#[derive(Clone)]
pub struct AppConfig(pub(crate) Rc<AppConfigInner>);
pub struct AppConfig(Rc<AppConfigInner>);
struct AppConfigInner {
secure: bool,
host: String,
addr: SocketAddr,
}
impl AppConfig {
pub(crate) fn new(inner: AppConfigInner) -> Self {
AppConfig(Rc::new(inner))
pub(crate) fn new(secure: bool, addr: SocketAddr, host: String) -> Self {
AppConfig(Rc::new(AppConfigInner { secure, addr, host }))
}
/// Set server host name.
/// Server host name.
///
/// Host name is used by application router as a hostname for url generation.
/// Check [ConnectionInfo](./struct.ConnectionInfo.html#method.host)
@ -153,19 +159,13 @@ impl AppConfig {
}
}
pub(crate) struct AppConfigInner {
pub(crate) secure: bool,
pub(crate) host: String,
pub(crate) addr: SocketAddr,
}
impl Default for AppConfigInner {
fn default() -> AppConfigInner {
AppConfigInner {
secure: false,
addr: "127.0.0.1:8080".parse().unwrap(),
host: "localhost:8080".to_owned(),
}
impl Default for AppConfig {
fn default() -> Self {
AppConfig::new(
false,
"127.0.0.1:8080".parse().unwrap(),
"localhost:8080".to_owned(),
)
}
}

View File

@ -56,7 +56,7 @@ pub(crate) trait DataFactory {
///
/// let app = App::new()
/// // Store `MyData` in application storage.
/// .register_data(data.clone())
/// .app_data(data.clone())
/// .service(
/// web::resource("/index.html").route(
/// web::get().to(index)));
@ -87,10 +87,10 @@ impl<T> Data<T> {
}
impl<T> Deref for Data<T> {
type Target = T;
type Target = Arc<T>;
fn deref(&self) -> &T {
self.0.as_ref()
fn deref(&self) -> &Arc<T> {
&self.0
}
}
@ -107,8 +107,8 @@ impl<T: 'static> FromRequest for Data<T> {
#[inline]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
if let Some(st) = req.get_app_data::<T>() {
ok(st)
if let Some(st) = req.app_data::<Data<T>>() {
ok(st.clone())
} else {
log::debug!(
"Failed to construct App-level Data extractor. \
@ -136,19 +136,22 @@ impl<T: 'static> DataFactory for Data<T> {
#[cfg(test)]
mod tests {
use actix_service::Service;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
use crate::http::StatusCode;
use crate::test::{init_service, TestRequest};
use crate::test::{self, init_service, TestRequest};
use crate::{web, App, HttpResponse};
#[actix_rt::test]
async fn test_data_extractor() {
let mut srv =
init_service(App::new().data(10usize).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
let mut srv = init_service(App::new().data("TEST".to_string()).service(
web::resource("/").to(|data: web::Data<String>| {
assert_eq!(data.to_lowercase(), "test");
HttpResponse::Ok()
}),
))
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
@ -165,9 +168,9 @@ mod tests {
}
#[actix_rt::test]
async fn test_register_data_extractor() {
async fn test_app_data_extractor() {
let mut srv =
init_service(App::new().register_data(Data::new(10usize)).service(
init_service(App::new().app_data(Data::new(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
@ -177,7 +180,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
let mut srv =
init_service(App::new().register_data(Data::new(10u32)).service(
init_service(App::new().app_data(Data::new(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
))
.await;
@ -220,7 +223,7 @@ mod tests {
let mut srv = init_service(App::new().data(1usize).service(
web::resource("/").data(10usize).route(web::get().to(
|data: web::Data<usize>| {
assert_eq!(*data, 10);
assert_eq!(**data, 10);
let _ = data.clone();
HttpResponse::Ok()
},
@ -232,4 +235,47 @@ mod tests {
let resp = srv.call(req).await.unwrap();
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

@ -1,4 +1,4 @@
#![deny(rust_2018_idioms, warnings)]
#![warn(rust_2018_idioms, warnings)]
#![allow(
clippy::needless_doctest_main,
clippy::type_complexity,
@ -20,7 +20,7 @@
//! web::resource("/{name}/{id}/index.html").to(index))
//! )
//! .bind("127.0.0.1:8080")?
//! .start()
//! .run()
//! .await
//! }
//! ```
@ -47,7 +47,7 @@
//! configure servers.
//!
//! * [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
//! [HttpResponse](struct.HttpResponse.html): These structs
@ -151,12 +151,13 @@ pub mod dev {
pub use actix_server::Server;
pub use actix_service::{Service, Transform};
pub(crate) fn insert_slash(path: &str) -> String {
let mut path = path.to_owned();
if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/');
};
path
pub(crate) fn insert_slash(mut patterns: Vec<String>) -> Vec<String> {
for path in &mut patterns {
if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/');
};
}
patterns
}
use crate::http::header::ContentEncoding;

View File

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

View File

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

View File

@ -8,7 +8,6 @@ use actix_router::{Path, Url};
use futures::future::{ok, Ready};
use crate::config::AppConfig;
use crate::data::Data;
use crate::error::UrlGenerationError;
use crate::extract::FromRequest;
use crate::info::ConnectionInfo;
@ -207,25 +206,21 @@ impl HttpRequest {
&self.0.config
}
/// Get an application data stored with `App::data()` method during
/// application configuration.
/// Get an application data object stored with `App::data` or `App::app_data`
/// methods during application configuration.
///
/// If `App::data` was used to store object, use `Data<T>`:
///
/// ```rust,ignore
/// let opt_t = req.app_data::<Data<T>>();
/// ```
pub fn app_data<T: 'static>(&self) -> Option<&T> {
if let Some(st) = self.0.app_data.get::<Data<T>>() {
if let Some(st) = self.0.app_data.get::<T>() {
Some(&st)
} else {
None
}
}
/// Get an application data stored with `App::data()` method during
/// application configuration.
pub fn get_app_data<T: 'static>(&self) -> Option<Data<T>> {
if let Some(st) = self.0.app_data.get::<Data<T>>() {
Some(st.clone())
} else {
None
}
}
}
impl HttpMessage for HttpRequest {
@ -467,8 +462,8 @@ mod tests {
}
#[actix_rt::test]
async fn test_app_data() {
let mut srv = init_service(App::new().data(10usize).service(
async fn test_data() {
let mut srv = init_service(App::new().app_data(10usize).service(
web::resource("/").to(|req: HttpRequest| {
if req.app_data::<usize>().is_some() {
HttpResponse::Ok()
@ -483,7 +478,7 @@ mod tests {
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let mut srv = init_service(App::new().data(10u32).service(
let mut srv = init_service(App::new().app_data(10u32).service(
web::resource("/").to(|req: HttpRequest| {
if req.app_data::<usize>().is_some() {
HttpResponse::Ok()

View File

@ -6,6 +6,7 @@ use std::rc::Rc;
use std::task::{Context, Poll};
use actix_http::{Error, Extensions, Response};
use actix_router::IntoPattern;
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{
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.
pub struct Resource<T = ResourceEndpoint> {
endpoint: T,
rdef: String,
rdef: Vec<String>,
name: Option<String>,
routes: Vec<Route>,
data: Option<Extensions>,
@ -58,12 +59,12 @@ pub struct Resource<T = ResourceEndpoint> {
}
impl Resource {
pub fn new(path: &str) -> Resource {
pub fn new<T: IntoPattern>(path: T) -> Resource {
let fref = Rc::new(RefCell::new(None));
Resource {
routes: Vec::new(),
rdef: path.to_string(),
rdef: path.patterns(),
name: None,
endpoint: ResourceEndpoint::new(fref.clone()),
factory_ref: fref,
@ -192,16 +193,13 @@ where
/// }
/// ```
pub fn data<U: 'static>(self, data: U) -> Self {
self.register_data(Data::new(data))
self.app_data(Data::new(data))
}
/// Set or override application data.
///
/// This method has the same effect as [`Resource::data`](#method.data),
/// except that instead of taking a value of some type `T`, it expects a
/// value of type `Data<T>`. Use a `Data<T>` extractor to retrieve its
/// value.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
if self.data.is_none() {
self.data = Some(Extensions::new());
}
@ -384,9 +382,9 @@ where
Some(std::mem::replace(&mut self.guards, Vec::new()))
};
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 {
ResourceDef::new(&self.rdef)
ResourceDef::new(self.rdef.clone())
};
if let Some(ref name) = self.name {
*rdef.name_mut() = name.clone();
@ -663,6 +661,23 @@ mod tests {
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]
async fn test_default_resource() {
let mut srv = init_service(
@ -754,19 +769,19 @@ mod tests {
App::new()
.data(1.0f64)
.data(1usize)
.register_data(web::Data::new('-'))
.app_data(web::Data::new('-'))
.service(
web::resource("/test")
.data(10usize)
.register_data(web::Data::new('*'))
.app_data(web::Data::new('*'))
.guard(guard::Get())
.to(
|data1: web::Data<usize>,
data2: web::Data<char>,
data3: web::Data<f64>| {
assert_eq!(*data1, 10);
assert_eq!(*data2, '*');
assert_eq!(*data3, 1.0);
assert_eq!(**data1, 10);
assert_eq!(**data2, '*');
assert_eq!(**data3, 1.0);
HttpResponse::Ok()
},
),

View File

@ -148,15 +148,13 @@ where
/// }
/// ```
pub fn data<U: 'static>(self, data: U) -> Self {
self.register_data(Data::new(data))
self.app_data(Data::new(data))
}
/// Set or override application data.
///
/// This method has the same effect as [`Scope::data`](#method.data), except
/// that instead of taking a value of some type `T`, it expects a value of
/// type `Data<T>`. Use a `Data<T>` extractor to retrieve its value.
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
/// This method overrides data stored with [`App::app_data()`](#method.app_data)
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
if self.data.is_none() {
self.data = Some(Extensions::new());
}
@ -1108,7 +1106,7 @@ mod tests {
web::scope("app").data(10usize).route(
"/t",
web::get().to(|data: web::Data<usize>| {
assert_eq!(*data, 10);
assert_eq!(**data, 10);
let _ = data.clone();
HttpResponse::Ok()
}),
@ -1122,21 +1120,17 @@ mod tests {
}
#[actix_rt::test]
async fn test_override_register_data() {
let mut srv = init_service(
App::new().register_data(web::Data::new(1usize)).service(
web::scope("app")
.register_data(web::Data::new(10usize))
.route(
"/t",
web::get().to(|data: web::Data<usize>| {
assert_eq!(*data, 10);
let _ = data.clone();
HttpResponse::Ok()
}),
),
async fn test_override_app_data() {
let mut srv = init_service(App::new().app_data(web::Data::new(1usize)).service(
web::scope("app").app_data(web::Data::new(10usize)).route(
"/t",
web::get().to(|data: web::Data<usize>| {
assert_eq!(**data, 10);
let _ = data.clone();
HttpResponse::Ok()
}),
),
)
))
.await;
let req = TestRequest::with_uri("/app/t").to_request();

View File

@ -2,26 +2,33 @@ use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use std::{fmt, io, net};
use actix_http::{
body::MessageBody, Error, HttpService, KeepAlive, Protocol, Request, Response,
};
use actix_http::{body::MessageBody, Error, HttpService, KeepAlive, Request, Response};
use actix_server::{Server, ServerBuilder};
use actix_service::{pipeline_factory, IntoServiceFactory, Service, ServiceFactory};
use futures::future::ok;
use actix_service::{map_config, IntoServiceFactory, Service, ServiceFactory};
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")]
use actix_tls::openssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
#[cfg(feature = "rustls")]
use actix_tls::rustls::ServerConfig as RustlsServerConfig;
use crate::config::AppConfig;
struct Socket {
scheme: &'static str,
addr: net::SocketAddr,
}
struct Config {
host: Option<String>,
keep_alive: KeepAlive,
client_timeout: u64,
client_shutdown: u64,
@ -31,35 +38,30 @@ struct Config {
///
/// Create new http server with application factory.
///
/// ```rust
/// use std::io;
/// ```rust,no_run
/// use actix_web::{web, App, HttpResponse, HttpServer};
///
/// fn main() -> io::Result<()> {
/// let sys = actix_rt::System::new("example"); // <- create Actix runtime
///
/// #[actix_rt::main]
/// async fn main() -> std::io::Result<()> {
/// HttpServer::new(
/// || App::new()
/// .service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:59090")?
/// .start();
///
/// # actix_rt::System::current().stop();
/// sys.run()
/// .run()
/// .await
/// }
/// ```
pub struct HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = AppConfig, Request = Request>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
B: MessageBody,
{
pub(super) factory: F,
pub(super) host: Option<String>,
config: Arc<Mutex<Config>>,
backlog: i32,
sockets: Vec<Socket>,
@ -71,7 +73,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = AppConfig, Request = Request>,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>> + 'static,
@ -82,8 +84,8 @@ where
pub fn new(factory: F) -> Self {
HttpServer {
factory,
host: None,
config: Arc::new(Mutex::new(Config {
host: None,
keep_alive: KeepAlive::Timeout(5),
client_timeout: 5000,
client_shutdown: 5000,
@ -184,8 +186,8 @@ where
/// documentation for more information.
///
/// By default host name is set to a "localhost" value.
pub fn server_hostname<T: AsRef<str>>(mut self, val: T) -> Self {
self.host = Some(val.as_ref().to_owned());
pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
self
}
@ -246,11 +248,17 @@ where
lst,
move || {
let c = cfg.lock().unwrap();
let cfg = AppConfig::new(
false,
addr,
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
);
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.local_addr(addr)
.finish(factory())
.finish(map_config(factory(), move |_| cfg.clone()))
.tcp()
},
)?;
@ -288,11 +296,16 @@ where
lst,
move || {
let c = cfg.lock().unwrap();
let cfg = AppConfig::new(
true,
addr,
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
);
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown)
.finish(factory())
.finish(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
},
)?;
@ -330,11 +343,16 @@ where
lst,
move || {
let c = cfg.lock().unwrap();
let cfg = AppConfig::new(
true,
addr,
c.host.clone().unwrap_or_else(|| format!("{}", addr)),
);
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown)
.finish(factory())
.finish(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
},
)?;
@ -435,24 +453,29 @@ where
let cfg = self.config.clone();
let factory = self.factory.clone();
// todo duplicated:
let socket_addr = net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
);
self.sockets.push(Socket {
scheme: "http",
addr: net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
),
addr: socket_addr,
});
let addr = format!("actix-web-service-{:?}", lst.local_addr()?);
self.builder = self.builder.listen_uds(addr, lst, move || {
let c = cfg.lock().unwrap();
let config = AppConfig::new(
false,
socket_addr,
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
);
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None))).and_then(
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.finish(factory()),
.finish(map_config(factory(), move |_| config.clone())),
)
})?;
Ok(self)
@ -470,12 +493,13 @@ where
let cfg = self.config.clone();
let factory = self.factory.clone();
let socket_addr = net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
);
self.sockets.push(Socket {
scheme: "http",
addr: net::SocketAddr::new(
net::IpAddr::V4(net::Ipv4Addr::new(127, 0, 0, 1)),
8080,
),
addr: socket_addr,
});
self.builder = self.builder.bind_uds(
@ -483,12 +507,17 @@ where
addr,
move || {
let c = cfg.lock().unwrap();
let config = AppConfig::new(
false,
socket_addr,
c.host.clone().unwrap_or_else(|| format!("{}", socket_addr)),
);
pipeline_factory(|io: UnixStream| ok((io, Protocol::Http1, None)))
.and_then(
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.finish(factory()),
.finish(map_config(factory(), move |_| config.clone())),
)
},
)?;
@ -500,7 +529,7 @@ impl<F, I, S, B> HttpServer<F, I, S, B>
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request>,
S: ServiceFactory<Config = AppConfig, Request = Request>,
S::Error: Into<Error>,
S::InitError: fmt::Debug,
S::Response: Into<Response<B>>,
@ -524,11 +553,11 @@ where
/// async fn main() -> io::Result<()> {
/// HttpServer::new(|| App::new().service(web::resource("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0")?
/// .start()
/// .run()
/// .await
/// }
/// ```
pub fn start(self) -> Server {
pub fn run(self) -> Server {
self.builder.start()
}
}

View File

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

View File

@ -1,5 +1,6 @@
//! Various helpers for Actix applications to use during testing.
use std::convert::TryFrom;
use std::net::SocketAddr;
use std::rc::Rc;
use std::sync::mpsc;
use std::{fmt, net, thread, time};
@ -10,9 +11,10 @@ use actix_http::http::{Error as HttpError, Method, StatusCode, Uri, Version};
use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{cookie::Cookie, ws, Extensions, HttpService, Request};
use actix_router::{Path, ResourceDef, Url};
use actix_rt::System;
use actix_server::Server;
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
use actix_rt::{time::delay_for, System};
use actix_service::{
map_config, IntoService, IntoServiceFactory, Service, ServiceFactory,
};
use awc::error::PayloadError;
use awc::{Client, ClientRequest, ClientResponse, Connector};
use bytes::{Bytes, BytesMut};
@ -25,9 +27,9 @@ use serde_json;
pub use actix_http::test::TestBuffer;
use crate::config::{AppConfig, AppConfigInner};
use crate::config::AppConfig;
use crate::data::Data;
use crate::dev::{Body, MessageBody, Payload};
use crate::dev::{Body, MessageBody, Payload, Server};
use crate::request::HttpRequestPool;
use crate::rmap::ResourceMap;
use crate::service::{ServiceRequest, ServiceResponse};
@ -63,7 +65,7 @@ pub fn default_service(
/// let mut app = test::init_service(
/// App::new()
/// .service(web::resource("/test").to(|| async { HttpResponse::Ok() }))
/// );
/// ).await;
///
/// // Create request object
/// let req = test::TestRequest::with_uri("/test").to_request();
@ -79,7 +81,7 @@ pub async fn init_service<R, S, B, E>(
where
R: IntoServiceFactory<S>,
S: ServiceFactory<
Config = (),
Config = AppConfig,
Request = Request,
Response = ServiceResponse<B>,
Error = E,
@ -87,7 +89,7 @@ where
S::InitError: std::fmt::Debug,
{
let srv = app.into_factory();
srv.new_service(()).await.unwrap()
srv.new_service(AppConfig::default()).await.unwrap()
}
/// Calls service and waits for response future completion.
@ -296,8 +298,9 @@ where
pub struct TestRequest {
req: HttpTestRequest,
rmap: ResourceMap,
config: AppConfigInner,
config: AppConfig,
path: Path<Url>,
peer_addr: Option<SocketAddr>,
app_data: Extensions,
}
@ -306,8 +309,9 @@ impl Default for TestRequest {
TestRequest {
req: HttpTestRequest::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
config: AppConfigInner::default(),
config: AppConfig::default(),
path: Path::new(Url::new(Uri::default())),
peer_addr: None,
app_data: Extensions::new(),
}
}
@ -407,6 +411,12 @@ impl TestRequest {
self
}
/// Set peer addr
pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
self.peer_addr = Some(addr);
self
}
/// Set request payload
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
self.req.set_payload(data);
@ -440,6 +450,13 @@ impl TestRequest {
self
}
/// Set application data. This is equivalent of `App::app_data()` method
/// for testing purpose.
pub fn app_data<T: 'static>(mut self, data: T) -> Self {
self.app_data.insert(data);
self
}
#[cfg(test)]
/// Set request config
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
@ -449,12 +466,15 @@ impl TestRequest {
/// Complete request creation and generate `Request` instance
pub fn to_request(mut self) -> Request {
self.req.finish()
let mut req = self.req.finish();
req.head_mut().peer_addr = self.peer_addr;
req
}
/// Complete request creation and generate `ServiceRequest` instance
pub fn to_srv_request(mut self) -> ServiceRequest {
let (head, payload) = self.req.finish().into_parts();
let (mut head, payload) = self.req.finish().into_parts();
head.peer_addr = self.peer_addr;
self.path.get_mut().update(&head.uri);
ServiceRequest::new(HttpRequest::new(
@ -462,7 +482,7 @@ impl TestRequest {
head,
payload,
Rc::new(self.rmap),
AppConfig::new(self.config),
self.config.clone(),
Rc::new(self.app_data),
HttpRequestPool::create(),
))
@ -475,7 +495,8 @@ impl TestRequest {
/// Complete request creation and generate `HttpRequest` instance
pub fn to_http_request(mut self) -> HttpRequest {
let (head, payload) = self.req.finish().into_parts();
let (mut head, payload) = self.req.finish().into_parts();
head.peer_addr = self.peer_addr;
self.path.get_mut().update(&head.uri);
HttpRequest::new(
@ -483,7 +504,7 @@ impl TestRequest {
head,
payload,
Rc::new(self.rmap),
AppConfig::new(self.config),
self.config.clone(),
Rc::new(self.app_data),
HttpRequestPool::create(),
)
@ -491,7 +512,8 @@ impl TestRequest {
/// Complete request creation and generate `HttpRequest` and `Payload` instances
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
let (head, payload) = self.req.finish().into_parts();
let (mut head, payload) = self.req.finish().into_parts();
head.peer_addr = self.peer_addr;
self.path.get_mut().update(&head.uri);
let req = HttpRequest::new(
@ -499,7 +521,7 @@ impl TestRequest {
head,
Payload::None,
Rc::new(self.rmap),
AppConfig::new(self.config),
self.config.clone(),
Rc::new(self.app_data),
HttpRequestPool::create(),
);
@ -538,7 +560,7 @@ pub fn start<F, I, S, B>(factory: F) -> TestServer
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request> + 'static,
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<HttpResponse<B>> + 'static,
@ -577,7 +599,7 @@ pub fn start_with<F, I, S, B>(cfg: TestServerConfig, factory: F) -> TestServer
where
F: Fn() -> I + Send + Clone + 'static,
I: IntoServiceFactory<S>,
S: ServiceFactory<Config = (), Request = Request> + 'static,
S: ServiceFactory<Config = AppConfig, Request = Request> + 'static,
S::Error: Into<Error> + 'static,
S::InitError: fmt::Debug,
S::Response: Into<HttpResponse<B>> + 'static,
@ -604,66 +626,84 @@ where
let ctimeout = cfg.client_timeout;
let builder = Server::build().workers(1).disable_signals();
match cfg.stream {
let srv = match cfg.stream {
StreamType::Tcp => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(factory())
.h1(map_config(factory(), move |_| cfg.clone()))
.tcp()
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(factory())
.h2(map_config(factory(), move |_| cfg.clone()))
.tcp()
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(factory())
.finish(map_config(factory(), move |_| cfg.clone()))
.tcp()
}),
},
#[cfg(feature = "openssl")]
StreamType::Openssl(acceptor) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(factory())
.h1(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(factory())
.h2(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(factory())
.finish(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
},
#[cfg(feature = "rustls")]
StreamType::Rustls(config) => match cfg.tp {
HttpVer::Http1 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(factory())
.h1(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(factory())
.h2(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
let cfg =
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(factory())
.finish(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
},
@ -671,11 +711,11 @@ where
.unwrap()
.start();
tx.send((System::current(), local_addr)).unwrap();
tx.send((System::current(), srv, local_addr)).unwrap();
sys.run()
});
let (system, addr) = rx.recv().unwrap();
let (system, server, addr) = rx.recv().unwrap();
let client = {
let connector = {
@ -690,7 +730,7 @@ where
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
Connector::new()
.conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000))
.timeout(time::Duration::from_millis(30000))
.ssl(builder.build())
.finish()
}
@ -698,7 +738,7 @@ where
{
Connector::new()
.conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000))
.timeout(time::Duration::from_millis(30000))
.finish()
}
};
@ -711,6 +751,7 @@ where
addr,
client,
system,
server,
}
}
@ -807,6 +848,7 @@ pub struct TestServer {
client: awc::Client,
system: actix_rt::System,
ssl: bool,
server: Server,
}
impl TestServer {
@ -895,15 +937,17 @@ impl TestServer {
self.ws_at("/").await
}
/// Stop http server
fn stop(&mut self) {
/// Gracefully stop http server
pub async fn stop(self) {
self.server.stop(true).await;
self.system.stop();
delay_for(time::Duration::from_millis(100)).await;
}
}
impl Drop for TestServer {
fn drop(&mut self) {
self.stop()
self.system.stop()
}
}
@ -915,7 +959,7 @@ mod tests {
use std::time::SystemTime;
use super::*;
use crate::{http::header, web, App, HttpResponse};
use crate::{http::header, web, App, HttpResponse, Responder};
#[actix_rt::test]
async fn test_basics() {
@ -924,19 +968,24 @@ mod tests {
.set(header::Date(SystemTime::now().into()))
.param("test", "123")
.data(10u32)
.app_data(20u64)
.peer_addr("127.0.0.1:8081".parse().unwrap())
.to_http_request();
assert!(req.headers().contains_key(header::CONTENT_TYPE));
assert!(req.headers().contains_key(header::DATE));
assert_eq!(
req.head().peer_addr,
Some("127.0.0.1:8081".parse().unwrap())
);
assert_eq!(&req.match_info()["test"], "123");
assert_eq!(req.version(), Version::HTTP_2);
let data = req.get_app_data::<u32>().unwrap();
assert!(req.get_app_data::<u64>().is_none());
assert_eq!(*data, 10);
let data = req.app_data::<Data<u32>>().unwrap();
assert!(req.app_data::<Data<u64>>().is_none());
assert_eq!(*data.get_ref(), 10);
assert!(req.app_data::<u64>().is_none());
let data = req.app_data::<u32>().unwrap();
assert_eq!(*data, 10);
assert!(req.app_data::<u32>().is_none());
let data = req.app_data::<u64>().unwrap();
assert_eq!(*data, 20);
}
#[actix_rt::test]
@ -1096,6 +1145,25 @@ mod tests {
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]
async fn test_actor() {
use actix::Actor;

View File

@ -190,7 +190,7 @@ impl<T: Serialize> Responder for Form<T> {
/// let app = App::new().service(
/// web::resource("/index.html")
/// // change `Form` extractor configuration
/// .data(
/// .app_data(
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
/// )
/// .route(web::get().to(index))
@ -365,7 +365,7 @@ where
.map_err(|_| UrlencodedError::Parse)
}
}
.boxed_local(),
.boxed_local(),
);
self.poll(cx)
}

View File

@ -224,17 +224,18 @@ where
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html").data(
/// // change json extractor configuration
/// web::Json::<Info>::configure(|cfg| {
/// cfg.limit(4096)
/// .content_type(|mime| { // <- accept text/plain content type
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
/// })
/// .error_handler(|err, req| { // <- create custom error response
/// error::InternalError::from_response(
/// err, HttpResponse::Conflict().finish()).into()
/// })
/// web::resource("/index.html")
/// .app_data(
/// // change json extractor configuration
/// web::Json::<Info>::configure(|cfg| {
/// cfg.limit(4096)
/// .content_type(|mime| { // <- accept text/plain content type
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
/// })
/// .error_handler(|err, req| { // <- create custom error response
/// error::InternalError::from_response(
/// err, HttpResponse::Conflict().finish()).into()
/// })
/// }))
/// .route(web::post().to(index))
/// );
@ -395,7 +396,7 @@ where
}
Ok(serde_json::from_slice::<U>(&body)?)
}
.boxed_local(),
.boxed_local(),
);
self.poll(cx)
@ -462,7 +463,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().limit(10).error_handler(|err, _| {
.app_data(JsonConfig::default().limit(10).error_handler(|err, _| {
let msg = MyObject {
name: "invalid request".to_string(),
};
@ -514,7 +515,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().limit(10))
.app_data(JsonConfig::default().limit(10))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
@ -531,7 +532,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(
.app_data(
JsonConfig::default()
.limit(10)
.error_handler(|_, _| JsonPayloadError::ContentType.into()),
@ -604,7 +605,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().limit(4096))
.app_data(JsonConfig::default().limit(4096))
.to_http_parts();
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
@ -622,7 +623,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
@ -642,7 +643,7 @@ mod tests {
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
.app_data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();

View File

@ -15,6 +15,8 @@ use crate::FromRequest;
#[derive(PartialEq, Eq, PartialOrd, Ord)]
/// Extract typed information from the request's path.
///
/// [**PathConfig**](struct.PathConfig.html) allows to configure extraction process.
///
/// ## Example
///
/// ```rust
@ -212,7 +214,7 @@ where
/// fn main() {
/// let app = App::new().service(
/// web::resource("/messages/{folder}")
/// .data(PathConfig::default().error_handler(|err, req| {
/// .app_data(PathConfig::default().error_handler(|err, req| {
/// error::InternalError::from_response(
/// err,
/// HttpResponse::Conflict().finish(),
@ -358,7 +360,7 @@ mod tests {
#[actix_rt::test]
async fn test_custom_err_handler() {
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
.data(PathConfig::default().error_handler(|err, _| {
.app_data(PathConfig::default().error_handler(|err, _| {
error::InternalError::from_response(
err,
HttpResponse::Conflict().finish(),

View File

@ -176,7 +176,7 @@ impl FromRequest for Bytes {
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html")
/// .data(String::configure(|cfg| { // <- limit size of the payload
/// .app_data(String::configure(|cfg| { // <- limit size of the payload
/// cfg.limit(4096)
/// }))
/// .route(web::get().to(index)) // <- register handler with extractor params
@ -229,7 +229,7 @@ impl FromRequest for String {
.ok_or_else(|| ErrorBadRequest("Can not decode body"))?)
}
}
.boxed_local(),
.boxed_local(),
)
}
}
@ -391,7 +391,7 @@ impl Future for HttpMessageBody {
}
Ok(body.freeze())
}
.boxed_local(),
.boxed_local(),
);
self.poll(cx)
}

View File

@ -19,6 +19,8 @@ use crate::request::HttpRequest;
/// be decoded into any type which depends upon data ordering e.g. tuples or tuple-structs.
/// Attempts to do so will *fail at runtime*.
///
/// [**QueryConfig**](struct.QueryConfig.html) allows to configure extraction process.
///
/// ## Example
///
/// ```rust
@ -185,7 +187,7 @@ where
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html").data(
/// web::resource("/index.html").app_data(
/// // change query extractor configuration
/// web::Query::<Info>::configure(|cfg| {
/// cfg.error_handler(|err, req| { // <- create custom error response
@ -273,7 +275,7 @@ mod tests {
#[actix_rt::test]
async fn test_custom_error_responder() {
let req = TestRequest::with_uri("/name/user1/")
.data(QueryConfig::default().error_handler(|e, _| {
.app_data(QueryConfig::default().error_handler(|e, _| {
let resp = HttpResponse::UnprocessableEntity().finish();
InternalError::from_response(e, resp).into()
}))

View File

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

View File

@ -30,7 +30,7 @@ default = []
openssl = ["open-ssl", "awc/openssl"]
[dependencies]
actix-service = "1.0.0"
actix-service = "1.0.1"
actix-codec = "0.2.0"
actix-connect = "1.0.0"
actix-utils = "1.0.3"
@ -55,5 +55,5 @@ time = "0.1"
open-ssl = { version="0.10", package="openssl", optional = true }
[dev-dependencies]
actix-web = "2.0.0-alpha.5"
actix-http = "1.0.0"
actix-web = "2.0.0-rc"
actix-http = "1.0.1"

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));
Connector::new()
.conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000))
.timeout(time::Duration::from_millis(30000))
.ssl(builder.build())
.finish()
}
@ -85,7 +85,7 @@ pub fn test_server<F: ServiceFactory<TcpStream>>(factory: F) -> TestServer {
{
Connector::new()
.conn_lifetime(time::Duration::from_secs(0))
.timeout(time::Duration::from_millis(3000))
.timeout(time::Duration::from_millis(30000))
.finish()
}
};

View File

@ -5,8 +5,7 @@ use std::{net, thread, time::Duration};
#[cfg(feature = "openssl")]
use open_ssl::ssl::SslAcceptorBuilder;
use actix_http::Response;
use actix_web::{web, App, HttpServer};
use actix_web::{web, App, HttpResponse, HttpServer};
fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
@ -28,7 +27,7 @@ async fn test_start() {
let srv = HttpServer::new(|| {
App::new().service(
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
web::resource("/").route(web::to(|| HttpResponse::Ok().body("test"))),
)
})
.workers(1)
@ -43,7 +42,7 @@ async fn test_start() {
.disable_signals()
.bind(format!("{}", addr))
.unwrap()
.start();
.run();
let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run();
@ -91,6 +90,8 @@ fn ssl_acceptor() -> std::io::Result<SslAcceptorBuilder> {
#[actix_rt::test]
#[cfg(feature = "openssl")]
async fn test_start_ssl() {
use actix_web::HttpRequest;
let addr = unused_addr();
let (tx, rx) = mpsc::channel();
@ -99,9 +100,10 @@ async fn test_start_ssl() {
let builder = ssl_acceptor().unwrap();
let srv = HttpServer::new(|| {
App::new().service(
web::resource("/").route(web::to(|| Response::Ok().body("test"))),
)
App::new().service(web::resource("/").route(web::to(|req: HttpRequest| {
assert!(req.app_config().secure());
HttpResponse::Ok().body("test")
})))
})
.workers(1)
.shutdown_timeout(1)
@ -109,7 +111,7 @@ async fn test_start_ssl() {
.disable_signals()
.bind_openssl(format!("{}", addr), builder)
.unwrap()
.start();
.run();
let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run();

View File

@ -675,7 +675,7 @@ async fn test_brotli_encoding_large() {
let srv = test::start_with(test::config().h1(), || {
App::new().service(
web::resource("/")
.data(web::PayloadConfig::new(320_000))
.app_data(web::PayloadConfig::new(320_000))
.route(web::to(move |body: Bytes| {
HttpResponse::Ok().streaming(TestBody::new(body, 10240))
})),