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

Compare commits

...

12 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
48476362a3 update changes 2019-12-20 17:59:34 +06:00
46 changed files with 353 additions and 180 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
## [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

View File

@ -1,6 +1,6 @@
[package]
name = "actix-web"
version = "2.0.0-rc"
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.1"
actix-utils = "1.0.4"
actix-router = "0.2.1"
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"
@ -115,4 +115,4 @@ actix-identity = { path = "actix-identity" }
actix-session = { path = "actix-session" }
actix-files = { path = "actix-files" }
actix-multipart = { path = "actix-multipart" }
awc = { path = "awc" }
awc = { path = "awc" }

View File

@ -1,15 +1,21 @@
## 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`.
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.
## 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<()> {
HttpServer::new(|| App::new().service(index))
.bind("127.0.0.1:8080")?
.start()
.run()
.await
}
```

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

@ -18,7 +18,7 @@ path = "src/lib.rs"
[dependencies]
actix-web = "2.0.0-rc"
actix-service = "1.0.0"
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,10 @@
# Changes
## [0.2.0] - 2019-12-xx
## [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.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Static files support for actix web."
readme = "README.md"
@ -20,7 +20,7 @@ path = "src/lib.rs"
[dependencies]
actix-web = { version = "2.0.0-rc", default-features = false }
actix-http = "1.0.1"
actix-service = "1.0.0"
actix-service = "1.0.1"
bitflags = "1"
bytes = "0.5.3"
futures = "0.3.1"

View File

@ -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,
};

View File

@ -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,9 @@
# Changes
## [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"

View File

@ -1,5 +1,9 @@
# Changes
## [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

@ -18,7 +18,7 @@ path = "src/lib.rs"
[dependencies]
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"
serde = "1.0"
serde_json = "1.0"

View File

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

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

@ -17,7 +17,7 @@ path = "src/lib.rs"
[dependencies]
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"
bytes = "0.5.3"
derive_more = "0.99.2"

View File

@ -1,5 +1,8 @@
# Changes
## [0.3.0] - 2019-12-20
* Release
## [0.3.0-alpha.4] - 2019-12-xx

View File

@ -23,7 +23,7 @@ cookie-session = ["actix-web/secure-cookies"]
[dependencies]
actix-web = "2.0.0-rc"
actix-service = "1.0.0"
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
//! }
//! ```

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

@ -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"

View File

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

View File

@ -4,7 +4,7 @@ use std::sync::Arc;
use actix_http::HttpService;
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::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok;
@ -63,11 +63,9 @@ async fn _test_connection_reuse_h2() {
.and_then(
HttpService::build()
.h2(map_config(
App::new()
.service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
)
.into_factory(),
App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
),
|_| AppConfig::default(),
))
.openssl(ssl_acceptor())

View File

@ -4,7 +4,7 @@ use std::sync::Arc;
use actix_http::HttpService;
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::{dev::AppConfig, web, App, HttpResponse};
use futures::future::ok;
@ -45,11 +45,9 @@ async fn test_connection_reuse_h2() {
.and_then(
HttpService::build()
.h2(map_config(
App::new()
.service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
)
.into_factory(),
App::new().service(
web::resource("/").route(web::to(|| HttpResponse::Ok())),
),
|_| AppConfig::default(),
))
.openssl(ssl_acceptor())

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

@ -136,10 +136,11 @@ 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]
@ -234,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

@ -20,7 +20,7 @@
//! web::resource("/{name}/{id}/index.html").to(index))
//! )
//! .bind("127.0.0.1:8080")?
//! .start()
//! .run()
//! .await
//! }
//! ```
@ -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

@ -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,
@ -381,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();
@ -660,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(

View File

@ -2,17 +2,19 @@ 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::{
map_config, 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")]
@ -36,21 +38,17 @@ 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>
@ -260,7 +258,7 @@ where
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.local_addr(addr)
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
.finish(map_config(factory(), move |_| cfg.clone()))
.tcp()
},
)?;
@ -307,7 +305,7 @@ where
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown)
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
.finish(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
},
)?;
@ -354,7 +352,7 @@ where
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.client_disconnect(c.client_shutdown)
.finish(map_config(factory().into_factory(), move |_| cfg.clone()))
.finish(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
},
)?;
@ -477,9 +475,7 @@ where
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.finish(map_config(factory().into_factory(), move |_| {
config.clone()
})),
.finish(map_config(factory(), move |_| config.clone())),
)
})?;
Ok(self)
@ -521,9 +517,7 @@ where
HttpService::build()
.keep_alive(c.keep_alive)
.client_timeout(c.client_timeout)
.finish(map_config(factory().into_factory(), move |_| {
config.clone()
})),
.finish(map_config(factory(), move |_| config.clone())),
)
},
)?;
@ -559,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

@ -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::{cookie::Cookie, ws, Extensions, HttpService, Request};
use actix_router::{Path, ResourceDef, Url};
use actix_rt::System;
use actix_server::Server;
use actix_rt::{time::delay_for, System};
use actix_service::{
map_config, IntoService, IntoServiceFactory, Service, ServiceFactory,
};
@ -30,7 +29,7 @@ pub use actix_http::test::TestBuffer;
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};
@ -66,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();
@ -627,14 +626,14 @@ 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(map_config(factory().into_factory(), move |_| cfg.clone()))
.h1(map_config(factory(), move |_| cfg.clone()))
.tcp()
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
@ -642,7 +641,7 @@ where
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
.h2(map_config(factory(), move |_| cfg.clone()))
.tcp()
}),
HttpVer::Both => builder.listen("test", tcp, move || {
@ -650,9 +649,7 @@ where
AppConfig::new(false, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(map_config(factory().into_factory(), move |_| {
cfg.clone()
}))
.finish(map_config(factory(), move |_| cfg.clone()))
.tcp()
}),
},
@ -663,7 +660,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
.h1(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
@ -671,7 +668,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
.h2(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
@ -679,9 +676,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(map_config(factory().into_factory(), move |_| {
cfg.clone()
}))
.finish(map_config(factory(), move |_| cfg.clone()))
.openssl(acceptor.clone())
}),
},
@ -692,7 +687,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h1(map_config(factory().into_factory(), move |_| cfg.clone()))
.h1(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
HttpVer::Http2 => builder.listen("test", tcp, move || {
@ -700,7 +695,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.h2(map_config(factory().into_factory(), move |_| cfg.clone()))
.h2(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
HttpVer::Both => builder.listen("test", tcp, move || {
@ -708,9 +703,7 @@ where
AppConfig::new(true, local_addr, format!("{}", local_addr));
HttpService::build()
.client_timeout(ctimeout)
.finish(map_config(factory().into_factory(), move |_| {
cfg.clone()
}))
.finish(map_config(factory(), move |_| cfg.clone()))
.rustls(config.clone())
}),
},
@ -718,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 = {
@ -758,6 +751,7 @@ where
addr,
client,
system,
server,
}
}
@ -854,6 +848,7 @@ pub struct TestServer {
client: awc::Client,
system: actix_rt::System,
ssl: bool,
server: Server,
}
impl TestServer {
@ -942,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()
}
}
@ -962,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() {
@ -1148,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

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

View File

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

View File

@ -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

@ -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"

View File

@ -42,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();
@ -111,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();