1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-05 10:25:21 +02:00

Compare commits

...

11 Commits

Author SHA1 Message Date
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
41 changed files with 332 additions and 178 deletions

67
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,67 @@
name: CI
on: [push, pull_request]
env:
VCPKGRS_DYNAMIC: 1
jobs:
build_and_test:
strategy:
fail-fast: false
matrix:
toolchain:
- x86_64-pc-windows-msvc
# - i686-pc-windows-msvc
- x86_64-apple-darwin
version:
- stable
- nightly
include:
- toolchain: x86_64-pc-windows-msvc
os: windows-latest
arch: x64
# - toolchain: i686-pc-windows-msvc
# os: windows-latest
# arch: x86
- toolchain: x86_64-apple-darwin
os: macOS-latest
name: ${{ matrix.version }} - ${{ matrix.toolchain }}
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@master
- name: Install ${{ matrix.version }}
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.version }}-${{ matrix.toolchain }}
default: true
- name: Install OpenSSL
if: matrix.os == 'windows-latest'
run: |
vcpkg integrate install
vcpkg install openssl:${{ matrix.arch }}-windows
- name: check nightly
if: matrix.version == 'nightly'
uses: actions-rs/cargo@v1
with:
command: check
args: --all --benches --bins --examples --tests
- name: check stable
if: matrix.version == 'stable'
uses: actions-rs/cargo@v1
with:
command: check
args: --all --bins --examples --tests
- name: tests
if: matrix.toolchain != 'x86_64-pc-windows-gnu'
uses: actions-rs/cargo@v1
with:
command: test
args: --all --all-features -- --nocapture

View File

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

View File

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

View File

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

View File

@ -53,7 +53,7 @@ async fn index(info: web::Path<(u32, String)>) -> impl Responder {
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index)) HttpServer::new(|| App::new().service(index))
.bind("127.0.0.1:8080")? .bind("127.0.0.1:8080")?
.start() .run()
.await .await
} }
``` ```

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,7 +18,7 @@ path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = { version = "2.0.0-rc", default-features = false, features = ["secure-cookies"] } actix-web = { version = "2.0.0-rc", default-features = false, features = ["secure-cookies"] }
actix-service = "1.0.0" actix-service = "1.0.1"
futures = "0.3.1" futures = "0.3.1"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"

View File

@ -294,7 +294,7 @@ where
Err(err) => Ok(req.error_response(err)), Err(err) => Ok(req.error_response(err)),
} }
} }
.boxed_local() .boxed_local()
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,7 +20,7 @@
//! web::resource("/{name}/{id}/index.html").to(index)) //! web::resource("/{name}/{id}/index.html").to(index))
//! ) //! )
//! .bind("127.0.0.1:8080")? //! .bind("127.0.0.1:8080")?
//! .start() //! .run()
//! .await //! .await
//! } //! }
//! ``` //! ```
@ -151,12 +151,13 @@ pub mod dev {
pub use actix_server::Server; pub use actix_server::Server;
pub use actix_service::{Service, Transform}; pub use actix_service::{Service, Transform};
pub(crate) fn insert_slash(path: &str) -> String { pub(crate) fn insert_slash(mut patterns: Vec<String>) -> Vec<String> {
let mut path = path.to_owned(); for path in &mut patterns {
if !path.is_empty() && !path.starts_with('/') { if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/'); path.insert(0, '/');
}; };
path }
patterns
} }
use crate::http::header::ContentEncoding; use crate::http::header::ContentEncoding;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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