1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-04 01:51:30 +02:00

Compare commits

...

60 Commits

Author SHA1 Message Date
acda1c075a prepare actix-web release 2019-06-17 12:23:30 +06:00
686e5f1595 update deps 2019-06-16 22:10:22 +06:00
d2b6502c7a prepare actix-http release 2019-06-16 21:59:22 +06:00
7c0f570845 Do not compress NoContent (204) responses #918 2019-06-16 21:54:17 +06:00
eaa371db8b update migration 2019-06-15 22:20:46 +06:00
d293ae2a69 fix nested resource map registration #915 2019-06-15 22:12:20 +06:00
d7ec241fd0 re-export identity and cors middleware 2019-06-15 21:47:06 +06:00
cd323f2ff1 Move cors middleware to actix-cors crate 2019-06-15 09:34:16 +06:00
bf48798bce Content-Length is 0 for NamedFile HEAD request #914 2019-06-13 15:27:21 +06:00
c8118e8411 fix path doc tests 2019-06-12 20:12:15 +06:00
e7ba67e1a8 rename PathPayloadError and test for path config 2019-06-12 17:02:45 +06:00
13e618b128 Added initial support for PathConfig, allows setting custom error handler. (#903) 2019-06-12 16:49:56 +06:00
36e6f0cb4b add "put" and "sput" methods for test server (#909) 2019-06-12 16:47:00 +06:00
7450ae37a7 Re-apply patch from #637 #894 2019-06-12 16:45:05 +06:00
2ffda29f9b Allow to test an app that uses async actors #897 2019-06-12 16:15:06 +06:00
ff724e239d move identity service separate crate 2019-06-12 15:52:48 +06:00
Bob
ee769832cf get_identity from HttpMessage (#908)
* get_identity from HttpMessage

* more doc for RequestIdentity
2019-06-12 09:26:46 +06:00
c4b7980b4f Upgraded actix-web dependency and set default-features to false (#895) 2019-06-07 09:34:56 +06:00
bfbac4f875 Upgraded actix-web dependency and set default-features to false (#900) 2019-06-07 09:34:30 +06:00
53e2f8090f Mark default enabled package features in the docs (#890) 2019-06-06 11:14:56 +06:00
e399e01a22 update readme 2019-06-05 09:02:44 +06:00
d9a62c4bbf add App::register_data() 2019-06-05 08:43:39 +06:00
a548b69679 fmt 2019-06-05 08:43:13 +06:00
ae64475d98 test-server release 2019-06-05 08:27:25 +06:00
a342b1289d prep awc release 2019-06-05 08:14:00 +06:00
38f04b75a7 update deps 2019-06-04 22:36:10 +06:00
a771540b16 prepare actix-web-codegen release 2019-06-04 22:33:43 +06:00
cf217d35a8 Added HEAD, CONNECT, OPTIONS and TRACE to the codegen (#886)
* Added HEAD, CONNECT, OPTIONS and TRACE to the codegen

* Add new macros to use statement

* Add patch to supported codegen http methods

* Update CHANGES.md

Added head, options, trace, connect and patch codegen changes to CHANGES.md
2019-06-04 22:30:43 +06:00
0e138e111f add external resource support on scope level 2019-06-03 23:41:32 +06:00
1fce4876f3 Scope configuration (#880)
* WIP: Scope configuarion

* Extensions: Fix into_iter()

* Scope: Fix tests

* Add ScopeConfig to web

Committing from mobile, if this doesn't look good it's because I haven't tested it...

* Scope Config: Use ServiceConfig instead

* Scope: Switch to ServiceConfig in doc

* ScopeConfig: Remove unnecessary changes, handle the case when data is empty

* ScopeConfig: Remove changes from actix-http
2019-06-03 23:12:37 +06:00
4a179d1ae1 prepare actix-session release 2019-06-03 10:52:43 +06:00
a780ea10e9 Guard cookie mod by cookie-session feature (#883)
Signed-off-by: Igor Gnatenko <i.gnatenko.brain@gmail.com>
2019-06-03 10:30:30 +06:00
6d2e190c8e prepare actix-files release 2019-06-02 13:09:21 +06:00
b1cfbdcf7a prepare actix-http release 2019-06-02 13:05:22 +06:00
24180f9014 Fix boundary parsing #876 2019-06-02 12:58:37 +06:00
15cdc680f6 Static files are incorrectly served as both chunked and with length #812 2019-06-01 17:57:40 +06:00
666756bfbe body helpers 2019-06-01 17:57:25 +06:00
a1b40f4314 add license files 2019-06-01 17:25:29 +06:00
29a0fe76d5 prepare actix-web-codegen release 2019-06-01 17:21:22 +06:00
7753b9da6d web-codegen: Add extra-traits to syn features (#879)
```rust
error[E0277]: `syn::attr::NestedMeta` doesn't implement `std::fmt::Debug`
   --> src/route.rs:149:57
    |
149 |                 attr => panic!("Unknown attribute{:?}", attr),
    |                                                         ^^^^ `syn::attr::NestedMeta` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
    |
    = help: the trait `std::fmt::Debug` is not implemented for `syn::attr::NestedMeta`
    = note: required because of the requirements on the impl of `std::fmt::Debug` for `&syn::attr::NestedMeta`
    = note: required by `std::fmt::Debug::fmt`
```
2019-06-01 14:13:45 +06:00
f1764bba43 Fix Logger time format (use rfc3339) (#867)
* Fix Logger time format (use rfc3339)

* Update change log
2019-05-31 12:09:21 +04:00
c2d7db7e06 prepare actix-web-actors release 2019-05-29 16:22:57 -07:00
21418c7414 prep actix-http release 2019-05-29 16:15:12 -07:00
fe781345d5 Add Migration steps for Custom Error (#869)
Adds migration steps for custom error in 1.0
2019-05-29 20:47:04 +04:00
a614be7cb5 Don't DISCONNECT from stream when reader is empty (#870)
* Don't DISCONNECT from stream when reader is empty

* Fix chunked transfer: poll_request before closing stream + Test
2019-05-29 20:37:42 +04:00
1eb89b8375 remove debug prints 2019-05-25 03:16:53 -07:00
aa626a1e72 handle disconnects 2019-05-25 03:16:46 -07:00
7f12b754e9 Handle socket read disconnect 2019-05-25 03:07:40 -07:00
3f196f469d update version 2019-05-25 02:13:04 -07:00
35eb378585 prepare actix-files release 2019-05-25 02:02:28 -07:00
6db625f55b Update actix-web dep to 1.0.0-rc (#864) 2019-05-25 01:52:23 -07:00
801cc2ed5d Cleaned unnecessary Option<_> around ServerBuilder in server.rs/HttpServer (#863) 2019-05-23 05:21:02 -07:00
ded1e86e7e Add ServiceRequest::set_payload() method 2019-05-22 21:25:51 -07:00
babf48c550 fix NamedFile last-modified check #820 2019-05-22 21:21:12 -07:00
d3e807f6e9 move Payload to inner http request 2019-05-22 11:49:27 -07:00
7746e785c1 re-export Service and Transform traits 2019-05-22 11:20:37 -07:00
4e141d7f5d Merge branch 'master' of github.com:actix/actix-web 2019-05-22 11:18:42 -07:00
12842871fe Clear http requests pool on app service drop #860 2019-05-22 11:18:33 -07:00
fc85ae4014 small documentation fix (#856) 2019-05-21 10:43:18 -07:00
5826f39dbe Add set_json method to TestRequest (#851)
- Takes a type which implements serde::Serialize, serializes it to JSON,
and sets it as the payload. The content-type is also set to JSON.
2019-05-18 19:36:28 -07:00
78 changed files with 1367 additions and 262 deletions

View File

@ -1,5 +1,54 @@
# Changes # Changes
## [1.0.1] - 2019-06-17
### Add
* Add support for PathConfig #903
* Add `middleware::identity::RequestIdentity` trait to `get_identity` from `HttpMessage`.
### Changes
* Move cors middleware to `actix-cors` crate.
* Move identity middleware to `actix-identity` crate.
* Disable default feature `secure-cookies`.
* Allow to test an app that uses async actors #897
* Re-apply patch from #637 #894
### Fixed
* HttpRequest::url_for is broken with nested scopes #915
## [1.0.0] - 2019-06-05
### Add
* Add `Scope::configure()` method.
* Add `ServiceRequest::set_payload()` method.
* Add `test::TestRequest::set_json()` convenience method to automatically
serialize data and set header in test requests.
* Add macros for head, options, trace, connect and patch http methods
### Changes
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
### Fixed
* Fix Logger request time format, and use rfc3339. #867
* Clear http requests pool on app service drop #860
## [1.0.0-rc] - 2019-05-18 ## [1.0.0-rc] - 2019-05-18
### Add ### Add

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-web" name = "actix-web"
version = "1.0.0-rc" version = "1.0.1"
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"
@ -31,9 +31,11 @@ members = [
".", ".",
"awc", "awc",
"actix-http", "actix-http",
"actix-cors",
"actix-files", "actix-files",
"actix-framed", "actix-framed",
"actix-session", "actix-session",
"actix-identity",
"actix-multipart", "actix-multipart",
"actix-web-actors", "actix-web-actors",
"actix-web-codegen", "actix-web-codegen",
@ -41,7 +43,7 @@ members = [
] ]
[features] [features]
default = ["brotli", "flate2-zlib", "secure-cookies", "client", "fail"] default = ["brotli", "flate2-zlib", "client", "fail", "depracated"]
# http client # http client
client = ["awc"] client = ["awc"]
@ -66,24 +68,31 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
# rustls # rustls
rust-tls = ["rustls", "actix-server/rust-tls"] rust-tls = ["rustls", "actix-server/rust-tls"]
# deprecated middlewares
depracated = ["actix-cors", "actix-identity"]
[dependencies] [dependencies]
actix-codec = "0.1.2" actix-codec = "0.1.2"
actix-service = "0.4.0" actix-service = "0.4.1"
actix-utils = "0.4.1" actix-utils = "0.4.1"
actix-router = "0.1.5" actix-router = "0.1.5"
actix-rt = "0.2.2" actix-rt = "0.2.2"
actix-web-codegen = "0.1.0" actix-web-codegen = "0.1.2"
actix-http = "0.2.0" actix-http = "0.2.4"
actix-server = "0.5.1" actix-server = "0.5.1"
actix-server-config = "0.1.1" actix-server-config = "0.1.1"
actix-threadpool = "0.1.0" actix-threadpool = "0.1.1"
awc = { version = "0.2.0", optional = true } awc = { version = "0.2.1", optional = true }
# deprecated middlewares
actix-cors = { version = "0.1.0", optional = true }
actix-identity = { version = "0.1.0", optional = true }
bytes = "0.4" bytes = "0.4"
derive_more = "0.14" derive_more = "0.15.0"
encoding = "0.2" encoding = "0.2"
futures = "0.1.25" futures = "0.1.25"
hashbrown = "0.3.0" hashbrown = "0.5.0"
log = "0.4" log = "0.4"
mime = "0.3" mime = "0.3"
net2 = "0.2.33" net2 = "0.2.33"
@ -100,9 +109,9 @@ openssl = { version="0.10", optional = true }
rustls = { version = "0.15", optional = true } rustls = { version = "0.15", optional = true }
[dev-dependencies] [dev-dependencies]
actix-http = { version = "0.2.0", features=["ssl", "brotli", "flate2-zlib"] } actix = { version = "0.8.3" }
actix-http-test = { version = "0.2.0", features=["ssl"] } actix-http = { version = "0.2.4", features=["ssl", "brotli", "flate2-zlib"] }
actix-files = { version = "0.1.0-beta.4" } actix-http-test = { version = "0.2.2", features=["ssl"] }
rand = "0.6" rand = "0.6"
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"
@ -116,7 +125,7 @@ opt-level = 3
codegen-units = 1 codegen-units = 1
[patch.crates-io] [patch.crates-io]
actix-web = { path = "." } # actix-web = { path = "." }
actix-http = { path = "actix-http" } actix-http = { path = "actix-http" }
actix-http-test = { path = "test-server" } actix-http-test = { path = "test-server" }
actix-web-codegen = { path = "actix-web-codegen" } actix-web-codegen = { path = "actix-web-codegen" }

View File

@ -1,4 +1,35 @@
## 1.0 ## 1.0.1
* Cors middleware has been moved to `actix-cors` crate
instead of
```rust
use actix_web::middleware::cors::Cors;
```
use
```rust
use actix_cors::Cors;
```
* Identity middleware has been moved to `actix-identity` crate
instead of
```rust
use actix_web::middleware::identity::{Identity, CookieIdentityPolicy, IdentityService};
```
use
```rust
use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
```
## 1.0.0
* Resource registration. 1.0 version uses generalized resource * Resource registration. 1.0 version uses generalized resource
registration via `.service()` method. registration via `.service()` method.
@ -238,6 +269,17 @@
* Actors support have been moved to `actix-web-actors` crate * Actors support have been moved to `actix-web-actors` crate
* Custom Error
Instead of error_response method alone, ResponseError now provides two methods: error_response and render_response respectively. Where, error_response creates the error response and render_response returns the error response to the caller.
Simplest migration from 0.7 to 1.0 shall include below method to the custom implementation of ResponseError:
```rust
fn render_response(&self) -> HttpResponse {
self.error_response()
}
```
## 0.7.15 ## 0.7.15

View File

@ -11,7 +11,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
* Multipart streams * Multipart streams
* Static assets * Static assets
* SSL support with OpenSSL or Rustls * SSL support with OpenSSL or Rustls
* Middlewares ([Logger, Session, CORS, CSRF, etc](https://actix.rs/docs/middleware/)) * Middlewares ([Logger, Session, CORS, etc](https://actix.rs/docs/middleware/))
* Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html) * Includes an asynchronous [HTTP client](https://actix.rs/actix-web/actix_web/client/index.html)
* Supports [Actix actor framework](https://github.com/actix/actix) * Supports [Actix actor framework](https://github.com/actix/actix)
@ -22,7 +22,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
* [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/) * [API Documentation (0.7)](https://docs.rs/actix-web/0.7.19/actix_web/)
* [Chat on gitter](https://gitter.im/actix/actix) * [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-web](https://crates.io/crates/actix-web) * Cargo package: [actix-web](https://crates.io/crates/actix-web)
* Minimum supported Rust version: 1.32 or later * Minimum supported Rust version: 1.34 or later
## Example ## Example

5
actix-cors/CHANGES.md Normal file
View File

@ -0,0 +1,5 @@
# Changes
## [0.1.0] - 2019-06-15
* Move cors middleware to separate crate

23
actix-cors/Cargo.toml Normal file
View File

@ -0,0 +1,23 @@
[package]
name = "actix-cors"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Cross-origin resource sharing (CORS) for Actix applications."
readme = "README.md"
keywords = ["web", "framework"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://docs.rs/actix-cors/"
license = "MIT/Apache-2.0"
edition = "2018"
#workspace = ".."
[lib]
name = "actix_cors"
path = "src/lib.rs"
[dependencies]
actix-web = "1.0.0"
actix-service = "0.4.0"
derive_more = "0.14.1"
futures = "0.1.25"

1
actix-cors/LICENSE-APACHE Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-cors/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

9
actix-cors/README.md Normal file
View File

@ -0,0 +1,9 @@
# Identity service for actix web framework [![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-identity)](https://crates.io/crates/actix-identity) [![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)
## Documentation & community resources
* [User Guide](https://actix.rs/docs/)
* [API Documentation](https://docs.rs/actix-identity/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
* Minimum supported Rust version: 1.34 or later

View File

@ -7,7 +7,7 @@
//! # Example //! # Example
//! //!
//! ```rust //! ```rust
//! use actix_web::middleware::cors::Cors; //! use actix_cors::Cors;
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer}; //! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
//! //!
//! fn index(req: HttpRequest) -> &'static str { //! fn index(req: HttpRequest) -> &'static str {
@ -42,17 +42,15 @@ use std::iter::FromIterator;
use std::rc::Rc; use std::rc::Rc;
use actix_service::{IntoTransform, Service, Transform}; use actix_service::{IntoTransform, Service, Transform};
use actix_web::dev::{RequestHead, ServiceRequest, ServiceResponse};
use actix_web::error::{Error, ResponseError, Result};
use actix_web::http::header::{self, HeaderName, HeaderValue};
use actix_web::http::{self, HttpTryFrom, Method, StatusCode, Uri};
use actix_web::HttpResponse;
use derive_more::Display; use derive_more::Display;
use futures::future::{ok, Either, Future, FutureResult}; use futures::future::{ok, Either, Future, FutureResult};
use futures::Poll; use futures::Poll;
use crate::dev::RequestHead;
use crate::error::{Error, ResponseError, Result};
use crate::http::header::{self, HeaderName, HeaderValue};
use crate::http::{self, HttpTryFrom, Method, StatusCode, Uri};
use crate::service::{ServiceRequest, ServiceResponse};
use crate::HttpResponse;
/// A set of errors that can occur during processing CORS /// A set of errors that can occur during processing CORS
#[derive(Debug, Display)] #[derive(Debug, Display)]
pub enum CorsError { pub enum CorsError {
@ -152,11 +150,11 @@ impl<T> AllOrSome<T> {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// use actix_cors::Cors;
/// use actix_web::http::header; /// use actix_web::http::header;
/// use actix_web::middleware::cors;
/// ///
/// # fn main() { /// # fn main() {
/// let cors = cors::Cors::new() /// let cors = Cors::new()
/// .allowed_origin("https://www.rust-lang.org/") /// .allowed_origin("https://www.rust-lang.org/")
/// .allowed_methods(vec!["GET", "POST"]) /// .allowed_methods(vec!["GET", "POST"])
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT]) /// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
@ -806,9 +804,9 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_service::{IntoService, Transform}; use actix_service::{IntoService, Transform};
use actix_web::test::{self, block_on, TestRequest};
use super::*; use super::*;
use crate::test::{self, block_on, TestRequest};
impl Cors { impl Cors {
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S> fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>

View File

@ -1,5 +1,20 @@
# Changes # Changes
## [0.1.2] - 2019-06-13
* Content-Length is 0 for NamedFile HEAD request #914
* Fix ring dependency from actix-web default features for #741
## [0.1.1] - 2019-06-01
* Static files are incorrectly served as both chunked and with length #812
## [0.1.0] - 2019-05-25
* NamedFile last-modified check always fails due to nano-seconds
in file modified date #820
## [0.1.0-beta.4] - 2019-05-12 ## [0.1.0-beta.4] - 2019-05-12
* Update actix-web to beta.4 * Update actix-web to beta.4

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-files" name = "actix-files"
version = "0.1.0-beta.4" version = "0.1.2"
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"
@ -18,12 +18,13 @@ name = "actix_files"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = "1.0.0-beta.5" actix-web = { version = "1.0.0", default-features = false }
actix-service = "0.4.0" actix-http = "0.2.4"
actix-service = "0.4.1"
bitflags = "1" bitflags = "1"
bytes = "0.4" bytes = "0.4"
futures = "0.1.25" futures = "0.1.25"
derive_more = "0.14" derive_more = "0.15.0"
log = "0.4" log = "0.4"
mime = "0.3" mime = "0.3"
mime_guess = "2.0.0-alpha" mime_guess = "2.0.0-alpha"
@ -31,4 +32,4 @@ percent-encoding = "1.0"
v_htmlescape = "0.4" v_htmlescape = "0.4"
[dev-dependencies] [dev-dependencies]
actix-web = { version = "1.0.0-beta.5", features=["ssl"] } actix-web = { version = "1.0.0", features=["ssl"] }

1
actix-files/LICENSE-APACHE Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-files/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -926,6 +926,29 @@ mod tests {
assert_eq!(bytes.freeze(), data); assert_eq!(bytes.freeze(), data);
} }
#[test]
fn test_head_content_length_headers() {
let mut srv = test::init_service(
App::new().service(Files::new("test", ".").index_file("tests/test.binary")),
);
// 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);
let contentlength = response
.headers()
.get(header::CONTENT_LENGTH)
.unwrap()
.to_str()
.unwrap();
assert_eq!(contentlength, "100");
}
#[test] #[test]
fn test_static_files_with_spaces() { fn test_static_files_with_spaces() {
let mut srv = test::init_service( let mut srv = test::init_service(

View File

@ -11,6 +11,7 @@ use bitflags::bitflags;
use mime; use mime;
use mime_guess::guess_mime_type; use mime_guess::guess_mime_type;
use actix_http::body::SizedStream;
use actix_web::http::header::{ use actix_web::http::header::{
self, ContentDisposition, DispositionParam, DispositionType, self, ContentDisposition, DispositionParam, DispositionType,
}; };
@ -337,7 +338,12 @@ impl Responder for NamedFile {
} else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) = } else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) =
(last_modified, req.get_header()) (last_modified, req.get_header())
{ {
m > since let t1: SystemTime = m.clone().into();
let t2: SystemTime = since.clone().into();
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
(Ok(t1), Ok(t2)) => t1 > t2,
_ => false,
}
} else { } else {
false false
}; };
@ -350,7 +356,12 @@ impl Responder for NamedFile {
} else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) = } else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) =
(last_modified, req.get_header()) (last_modified, req.get_header())
{ {
m <= since let t1: SystemTime = m.clone().into();
let t2: SystemTime = since.clone().into();
match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) {
(Ok(t1), Ok(t2)) => t1 <= t2,
_ => false,
}
} else { } else {
false false
}; };
@ -411,20 +422,16 @@ impl Responder for NamedFile {
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish()); return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
} }
if *req.method() == Method::HEAD { let reader = ChunkedReadFile {
Ok(resp.finish()) offset,
} else { size: length,
let reader = ChunkedReadFile { file: Some(self.file),
offset, fut: None,
size: length, counter: 0,
file: Some(self.file), };
fut: None, if offset != 0 || length != self.md.len() {
counter: 0, return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
}; };
if offset != 0 || length != self.md.len() { Ok(resp.body(SizedStream::new(length, reader)))
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
};
Ok(resp.streaming(reader))
}
} }
} }

View File

@ -1,5 +1,39 @@
# Changes # Changes
## [0.2.4] - 2019-06-16
### Fixed
* Do not compress NoContent (204) responses #918
## [0.2.3] - 2019-06-02
### Added
* Debug impl for ResponseBuilder
* From SizedStream and BodyStream for Body
### Changed
* SizedStream uses u64
## [0.2.2] - 2019-05-29
### Fixed
* Parse incoming stream before closing stream on disconnect #868
## [0.2.1] - 2019-05-25
### Fixed
* Handle socket read disconnect
## [0.2.0] - 2019-05-12 ## [0.2.0] - 2019-05-12
### Changed ### Changed

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-http" name = "actix-http"
version = "0.2.0" version = "0.2.4"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http primitives" description = "Actix http primitives"
readme = "README.md" readme = "README.md"
@ -47,7 +47,7 @@ secure-cookies = ["ring"]
actix-service = "0.4.0" actix-service = "0.4.0"
actix-codec = "0.1.2" actix-codec = "0.1.2"
actix-connect = "0.2.0" actix-connect = "0.2.0"
actix-utils = "0.4.0" actix-utils = "0.4.1"
actix-server-config = "0.1.1" actix-server-config = "0.1.1"
actix-threadpool = "0.1.0" actix-threadpool = "0.1.0"
@ -56,11 +56,11 @@ bitflags = "1.0"
bytes = "0.4" bytes = "0.4"
byteorder = "1.2" byteorder = "1.2"
copyless = "0.1.2" copyless = "0.1.2"
derive_more = "0.14" derive_more = "0.15.0"
either = "1.5.2" either = "1.5.2"
encoding = "0.2" encoding = "0.2"
futures = "0.1.25" futures = "0.1.25"
hashbrown = "0.3.0" hashbrown = "0.5.0"
h2 = "0.1.16" h2 = "0.1.16"
http = "0.1.17" http = "0.1.17"
httparse = "1.3" httparse = "1.3"
@ -81,7 +81,7 @@ time = "0.1.42"
tokio-tcp = "0.1.3" tokio-tcp = "0.1.3"
tokio-timer = "0.2.8" tokio-timer = "0.2.8"
tokio-current-thread = "0.1" tokio-current-thread = "0.1"
trust-dns-resolver = { version="0.11.0", default-features = false } trust-dns-resolver = { version="0.11.1", default-features = false }
# for secure cookie # for secure cookie
ring = { version = "0.14.6", optional = true } ring = { version = "0.14.6", optional = true }

View File

@ -234,6 +234,25 @@ impl From<BytesMut> for Body {
} }
} }
impl<S> From<SizedStream<S>> for Body
where
S: Stream<Item = Bytes, Error = Error> + 'static,
{
fn from(s: SizedStream<S>) -> Body {
Body::from_message(s)
}
}
impl<S, E> From<BodyStream<S, E>> for Body
where
S: Stream<Item = Bytes, Error = E> + 'static,
E: Into<Error> + 'static,
{
fn from(s: BodyStream<S, E>) -> Body {
Body::from_message(s)
}
}
impl MessageBody for Bytes { impl MessageBody for Bytes {
fn size(&self) -> BodySize { fn size(&self) -> BodySize {
BodySize::Sized(self.len()) BodySize::Sized(self.len())
@ -366,7 +385,7 @@ where
/// Type represent streaming body. This body implementation should be used /// Type represent streaming body. This body implementation should be used
/// if total size of stream is known. Data get sent as is without using transfer encoding. /// if total size of stream is known. Data get sent as is without using transfer encoding.
pub struct SizedStream<S> { pub struct SizedStream<S> {
size: usize, size: u64,
stream: S, stream: S,
} }
@ -374,7 +393,7 @@ impl<S> SizedStream<S>
where where
S: Stream<Item = Bytes, Error = Error>, S: Stream<Item = Bytes, Error = Error>,
{ {
pub fn new(size: usize, stream: S) -> Self { pub fn new(size: u64, stream: S) -> Self {
SizedStream { size, stream } SizedStream { size, stream }
} }
} }
@ -384,7 +403,7 @@ where
S: Stream<Item = Bytes, Error = Error>, S: Stream<Item = Bytes, Error = Error>,
{ {
fn size(&self) -> BodySize { fn size(&self) -> BodySize {
BodySize::Sized(self.size) BodySize::Sized64(self.size)
} }
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> { fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {

View File

@ -33,6 +33,7 @@ impl<B: MessageBody> Encoder<B> {
) -> ResponseBody<Encoder<B>> { ) -> ResponseBody<Encoder<B>> {
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING) let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|| head.status == StatusCode::SWITCHING_PROTOCOLS || head.status == StatusCode::SWITCHING_PROTOCOLS
|| head.status == StatusCode::NO_CONTENT
|| encoding == ContentEncoding::Identity || encoding == ContentEncoding::Identity
|| encoding == ContentEncoding::Auto); || encoding == ContentEncoding::Auto);

View File

@ -583,6 +583,9 @@ where
self.ka_timer = Some(Delay::new(interval)); self.ka_timer = Some(Delay::new(interval));
} else { } else {
self.flags.insert(Flags::READ_DISCONNECT); self.flags.insert(Flags::READ_DISCONNECT);
if let Some(mut payload) = self.payload.take() {
payload.set_error(PayloadError::Incomplete(None));
}
return Ok(()); return Ok(());
} }
} else { } else {
@ -690,15 +693,21 @@ where
} }
} else { } else {
// read socket into a buf // read socket into a buf
if !inner.flags.contains(Flags::READ_DISCONNECT) { let should_disconnect =
if let Some(true) = if !inner.flags.contains(Flags::READ_DISCONNECT) {
read_available(&mut inner.io, &mut inner.read_buf)? read_available(&mut inner.io, &mut inner.read_buf)?
{ } else {
inner.flags.insert(Flags::READ_DISCONNECT) None
} };
}
inner.poll_request()?; inner.poll_request()?;
if let Some(true) = should_disconnect {
inner.flags.insert(Flags::READ_DISCONNECT);
if let Some(mut payload) = inner.payload.take() {
payload.feed_eof();
}
};
loop { loop {
if inner.write_buf.remaining_mut() < LW_BUFFER_SIZE { if inner.write_buf.remaining_mut() < LW_BUFFER_SIZE {
inner.write_buf.reserve(HW_BUFFER_SIZE); inner.write_buf.reserve(HW_BUFFER_SIZE);

View File

@ -764,6 +764,25 @@ impl IntoFuture for ResponseBuilder {
} }
} }
impl fmt::Debug for ResponseBuilder {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let head = self.head.as_ref().unwrap();
let res = writeln!(
f,
"\nResponseBuilder {:?} {}{}",
head.version,
head.status,
head.reason.unwrap_or(""),
);
let _ = writeln!(f, " headers:");
for (key, val) in head.headers.iter() {
let _ = writeln!(f, " {:?}: {:?}", key, val);
}
res
}
}
/// Helper converters /// Helper converters
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response { impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
fn from(res: Result<I, E>) -> Self { fn from(res: Result<I, E>) -> Self {

View File

@ -9,9 +9,9 @@ use actix_service::{new_service_cfg, service_fn, NewService};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future::{self, ok, Future}; use futures::future::{self, ok, Future};
use futures::stream::{once, Stream}; use futures::stream::{once, Stream};
use regex::Regex;
use tokio_timer::sleep; use tokio_timer::sleep;
use actix_http::body::Body;
use actix_http::error::PayloadError; use actix_http::error::PayloadError;
use actix_http::{ use actix_http::{
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response, body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
@ -215,6 +215,54 @@ fn test_expect_continue_h1() {
assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n")); assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));
} }
#[test]
fn test_chunked_payload() {
let chunk_sizes = vec![32768, 32, 32768];
let total_size: usize = chunk_sizes.iter().sum();
let srv = TestServer::new(|| {
HttpService::build().h1(|mut request: Request| {
request
.take_payload()
.map_err(|e| panic!(format!("Error reading payload: {}", e)))
.fold(0usize, |acc, chunk| future::ok::<_, ()>(acc + chunk.len()))
.map(|req_size| Response::Ok().body(format!("size={}", req_size)))
})
});
let returned_size = {
let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
let _ = stream
.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n");
for chunk_size in chunk_sizes.iter() {
let mut bytes = Vec::new();
let random_bytes: Vec<u8> =
(0..*chunk_size).map(|_| rand::random::<u8>()).collect();
bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes());
bytes.extend(&random_bytes[..]);
bytes.extend(b"\r\n");
let _ = stream.write_all(&bytes);
}
let _ = stream.write_all(b"0\r\n\r\n");
stream.shutdown(net::Shutdown::Write).unwrap();
let mut data = String::new();
let _ = stream.read_to_string(&mut data);
let re = Regex::new(r"size=(\d+)").unwrap();
let size: usize = match re.captures(&data) {
Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
None => panic!(format!("Failed to find size in HTTP Response: {}", data)),
};
size
};
assert_eq!(returned_size, total_size);
}
#[test] #[test]
fn test_slow_request() { fn test_slow_request() {
let srv = TestServer::new(|| { let srv = TestServer::new(|| {
@ -775,8 +823,7 @@ fn test_h1_body_length() {
HttpService::build().h1(|_| { HttpService::build().h1(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
Response::Ok() Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
.body(Body::from_message(body::SizedStream::new(STR.len(), body))),
) )
}) })
}); });
@ -801,9 +848,10 @@ fn test_h2_body_length() {
HttpService::build() HttpService::build()
.h2(|_| { .h2(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().body(Body::from_message( ok::<_, ()>(
body::SizedStream::new(STR.len(), body), Response::Ok()
))) .body(body::SizedStream::new(STR.len() as u64, body)),
)
}) })
.map_err(|_| ()), .map_err(|_| ()),
) )

View File

@ -0,0 +1,5 @@
# Changes
## [0.1.0] - 2019-06-xx
* Move identity middleware to separate crate

30
actix-identity/Cargo.toml Normal file
View File

@ -0,0 +1,30 @@
[package]
name = "actix-identity"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Identity service for actix web framework."
readme = "README.md"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://actix.rs"
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 = "1.0.0", default-features = false, features = ["secure-cookies"] }
actix-service = "0.4.0"
futures = "0.1.25"
serde = "1.0"
serde_json = "1.0"
time = "0.1.42"
[dev-dependencies]
actix-rt = "0.2.2"
actix-http = "0.2.3"
bytes = "0.4"

View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-identity/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

9
actix-identity/README.md Normal file
View File

@ -0,0 +1,9 @@
# Identity service for actix web framework [![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-identity)](https://crates.io/crates/actix-identity) [![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)
## Documentation & community resources
* [User Guide](https://actix.rs/docs/)
* [API Documentation](https://docs.rs/actix-identity/)
* [Chat on gitter](https://gitter.im/actix/actix)
* Cargo package: [actix-session](https://crates.io/crates/actix-identity)
* Minimum supported Rust version: 1.34 or later

View File

@ -10,12 +10,11 @@
//! uses cookies as identity storage. //! uses cookies as identity storage.
//! //!
//! To access current request identity //! To access current request identity
//! [**Identity**](trait.Identity.html) extractor should be used. //! [**Identity**](struct.Identity.html) extractor should be used.
//! //!
//! ```rust //! ```rust
//! use actix_web::middleware::identity::Identity;
//! use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
//! use actix_web::*; //! use actix_web::*;
//! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
//! //!
//! fn index(id: Identity) -> String { //! fn index(id: Identity) -> String {
//! // access request identity //! // access request identity
@ -39,7 +38,7 @@
//! fn main() { //! fn main() {
//! let app = App::new().wrap(IdentityService::new( //! let app = App::new().wrap(IdentityService::new(
//! // <- create identity middleware //! // <- create identity middleware
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend //! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie identity policy
//! .name("auth-cookie") //! .name("auth-cookie")
//! .secure(false))) //! .secure(false)))
//! .service(web::resource("/index.html").to(index)) //! .service(web::resource("/index.html").to(index))
@ -57,17 +56,17 @@ use futures::{Future, IntoFuture, Poll};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use time::Duration; use time::Duration;
use crate::cookie::{Cookie, CookieJar, Key, SameSite}; use actix_web::cookie::{Cookie, CookieJar, Key, SameSite};
use crate::error::{Error, Result}; use actix_web::dev::{Extensions, Payload, ServiceRequest, ServiceResponse};
use crate::http::header::{self, HeaderValue}; use actix_web::error::{Error, Result};
use crate::service::{ServiceRequest, ServiceResponse}; use actix_web::http::header::{self, HeaderValue};
use crate::{dev::Payload, FromRequest, HttpMessage, HttpRequest}; use actix_web::{FromRequest, HttpMessage, HttpRequest};
/// The extractor type to obtain your identity from a request. /// The extractor type to obtain your identity from a request.
/// ///
/// ```rust /// ```rust
/// use actix_web::*; /// use actix_web::*;
/// use actix_web::middleware::identity::Identity; /// use actix_identity::Identity;
/// ///
/// fn index(id: Identity) -> Result<String> { /// fn index(id: Identity) -> Result<String> {
/// // access request identity /// // access request identity
@ -96,11 +95,7 @@ impl Identity {
/// Return the claimed identity of the user associated request or /// Return the claimed identity of the user associated request or
/// ``None`` if no identity can be found associated with the request. /// ``None`` if no identity can be found associated with the request.
pub fn identity(&self) -> Option<String> { pub fn identity(&self) -> Option<String> {
if let Some(id) = self.0.extensions().get::<IdentityItem>() { Identity::get_identity(&self.0.extensions())
id.id.clone()
} else {
None
}
} }
/// Remember identity. /// Remember identity.
@ -119,6 +114,14 @@ impl Identity {
id.changed = true; id.changed = true;
} }
} }
fn get_identity(extensions: &Extensions) -> Option<String> {
if let Some(id) = extensions.get::<IdentityItem>() {
id.id.clone()
} else {
None
}
}
} }
struct IdentityItem { struct IdentityItem {
@ -126,11 +129,28 @@ struct IdentityItem {
changed: bool, changed: bool,
} }
/// Helper trait that allows to get Identity.
///
/// It could be used in middleware but identity policy must be set before any other middleware that needs identity
/// RequestIdentity is implemented both for `ServiceRequest` and `HttpRequest`.
pub trait RequestIdentity {
fn get_identity(&self) -> Option<String>;
}
impl<T> RequestIdentity for T
where
T: HttpMessage,
{
fn get_identity(&self) -> Option<String> {
Identity::get_identity(&self.extensions())
}
}
/// Extractor implementation for Identity type. /// Extractor implementation for Identity type.
/// ///
/// ```rust /// ```rust
/// # use actix_web::*; /// # use actix_web::*;
/// use actix_web::middleware::identity::Identity; /// use actix_identity::Identity;
/// ///
/// fn index(id: Identity) -> String { /// fn index(id: Identity) -> String {
/// // access request identity /// // access request identity
@ -177,7 +197,7 @@ pub trait IdentityPolicy: Sized + 'static {
/// ///
/// ```rust /// ```rust
/// use actix_web::App; /// use actix_web::App;
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService}; /// use actix_identity::{CookieIdentityPolicy, IdentityService};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().wrap(IdentityService::new( /// let app = App::new().wrap(IdentityService::new(
@ -442,9 +462,8 @@ impl CookieIdentityInner {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web;
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
/// use actix_web::App; /// use actix_web::App;
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().wrap(IdentityService::new( /// let app = App::new().wrap(IdentityService::new(
@ -590,13 +609,13 @@ impl IdentityPolicy for CookieIdentityPolicy {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use crate::http::StatusCode;
use crate::test::{self, TestRequest};
use crate::{web, App, HttpResponse};
use std::borrow::Borrow; use std::borrow::Borrow;
use super::*;
use actix_web::http::StatusCode;
use actix_web::test::{self, TestRequest};
use actix_web::{web, App, Error, HttpResponse};
const COOKIE_KEY_MASTER: [u8; 32] = [0; 32]; const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
const COOKIE_NAME: &'static str = "actix_auth"; const COOKIE_NAME: &'static str = "actix_auth";
const COOKIE_LOGIN: &'static str = "test"; const COOKIE_LOGIN: &'static str = "test";
@ -717,8 +736,8 @@ mod tests {
f: F, f: F,
) -> impl actix_service::Service< ) -> impl actix_service::Service<
Request = actix_http::Request, Request = actix_http::Request,
Response = ServiceResponse<actix_http::body::Body>, Response = ServiceResponse<actix_web::body::Body>,
Error = actix_http::Error, Error = Error,
> { > {
test::init_service( test::init_service(
App::new() App::new()

View File

@ -1,12 +1,24 @@
# Changes # Changes
## [0.1.3] - 2019-06-06
* Fix ring dependency from actix-web default features for #741.
## [0.1.2] - 2019-06-02
* Fix boundary parsing #876
## [0.1.1] - 2019-05-25
* Fix disconnect handling #834
## [0.1.0] - 2019-05-18 ## [0.1.0] - 2019-05-18
* Release * Release
## [0.1.0-beta.4] - 2019-05-12 ## [0.1.0-beta.4] - 2019-05-12
* Handle cancellation of uploads #834 #736 * Handle cancellation of uploads #736
* Upgrade to actix-web 1.0.0-beta.4 * Upgrade to actix-web 1.0.0-beta.4

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-multipart" name = "actix-multipart"
version = "0.1.0" version = "0.1.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Multipart support for actix web framework." description = "Multipart support for actix web framework."
readme = "README.md" readme = "README.md"
@ -18,10 +18,10 @@ name = "actix_multipart"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = "1.0.0-rc" actix-web = { version = "1.0.0", default-features = false }
actix-service = "0.4.0" actix-service = "0.4.1"
bytes = "0.4" bytes = "0.4"
derive_more = "0.14" derive_more = "0.15.0"
httparse = "1.3" httparse = "1.3"
futures = "0.1.25" futures = "0.1.25"
log = "0.4" log = "0.4"
@ -31,4 +31,4 @@ twoway = "0.2"
[dev-dependencies] [dev-dependencies]
actix-rt = "0.2.2" actix-rt = "0.2.2"
actix-http = "0.2.0" actix-http = "0.2.4"

View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-multipart/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -128,7 +128,7 @@ impl InnerMultipart {
fn read_headers( fn read_headers(
payload: &mut PayloadBuffer, payload: &mut PayloadBuffer,
) -> Result<Option<HeaderMap>, MultipartError> { ) -> Result<Option<HeaderMap>, MultipartError> {
match payload.read_until(b"\r\n\r\n") { match payload.read_until(b"\r\n\r\n")? {
None => { None => {
if payload.eof { if payload.eof {
Err(MultipartError::Incomplete) Err(MultipartError::Incomplete)
@ -167,7 +167,7 @@ impl InnerMultipart {
boundary: &str, boundary: &str,
) -> Result<Option<bool>, MultipartError> { ) -> Result<Option<bool>, MultipartError> {
// TODO: need to read epilogue // TODO: need to read epilogue
match payload.readline() { match payload.readline()? {
None => { None => {
if payload.eof { if payload.eof {
Ok(Some(true)) Ok(Some(true))
@ -200,7 +200,7 @@ impl InnerMultipart {
) -> Result<Option<bool>, MultipartError> { ) -> Result<Option<bool>, MultipartError> {
let mut eof = false; let mut eof = false;
loop { loop {
match payload.readline() { match payload.readline()? {
Some(chunk) => { Some(chunk) => {
if chunk.is_empty() { if chunk.is_empty() {
return Err(MultipartError::Boundary); return Err(MultipartError::Boundary);
@ -481,7 +481,7 @@ impl InnerField {
if *size == 0 { if *size == 0 {
Ok(Async::Ready(None)) Ok(Async::Ready(None))
} else { } else {
match payload.read_max(*size) { match payload.read_max(*size)? {
Some(mut chunk) => { Some(mut chunk) => {
let len = cmp::min(chunk.len() as u64, *size); let len = cmp::min(chunk.len() as u64, *size);
*size -= len; *size -= len;
@ -512,7 +512,11 @@ impl InnerField {
let len = payload.buf.len(); let len = payload.buf.len();
if len == 0 { if len == 0 {
return Ok(Async::NotReady); return if payload.eof {
Err(MultipartError::Incomplete)
} else {
Ok(Async::NotReady)
};
} }
// check boundary // check boundary
@ -533,8 +537,6 @@ impl InnerField {
if &payload.buf[b_len..b_size] == boundary.as_bytes() { if &payload.buf[b_len..b_size] == boundary.as_bytes() {
// found boundary // found boundary
return Ok(Async::Ready(None)); return Ok(Async::Ready(None));
} else {
pos = b_size;
} }
} }
} }
@ -572,7 +574,7 @@ impl InnerField {
} }
} }
} else { } else {
return Ok(Async::Ready(Some(payload.buf.take().freeze()))); Ok(Async::Ready(Some(payload.buf.take().freeze())))
}; };
} }
} }
@ -597,7 +599,7 @@ impl InnerField {
} }
} }
match payload.readline() { match payload.readline()? {
None => Async::Ready(None), None => Async::Ready(None),
Some(line) => { Some(line) => {
if line.as_ref() != b"\r\n" { if line.as_ref() != b"\r\n" {
@ -749,23 +751,31 @@ impl PayloadBuffer {
} }
} }
fn read_max(&mut self, size: u64) -> Option<Bytes> { fn read_max(&mut self, size: u64) -> Result<Option<Bytes>, MultipartError> {
if !self.buf.is_empty() { if !self.buf.is_empty() {
let size = std::cmp::min(self.buf.len() as u64, size) as usize; let size = std::cmp::min(self.buf.len() as u64, size) as usize;
Some(self.buf.split_to(size).freeze()) Ok(Some(self.buf.split_to(size).freeze()))
} else if self.eof {
Err(MultipartError::Incomplete)
} else { } else {
None Ok(None)
} }
} }
/// Read until specified ending /// Read until specified ending
pub fn read_until(&mut self, line: &[u8]) -> Option<Bytes> { pub fn read_until(&mut self, line: &[u8]) -> Result<Option<Bytes>, MultipartError> {
twoway::find_bytes(&self.buf, line) let res = twoway::find_bytes(&self.buf, line)
.map(|idx| self.buf.split_to(idx + line.len()).freeze()) .map(|idx| self.buf.split_to(idx + line.len()).freeze());
if res.is_none() && self.eof {
Err(MultipartError::Incomplete)
} else {
Ok(res)
}
} }
/// Read bytes until new line delimiter /// Read bytes until new line delimiter
pub fn readline(&mut self) -> Option<Bytes> { pub fn readline(&mut self) -> Result<Option<Bytes>, MultipartError> {
self.read_until(b"\n") self.read_until(b"\n")
} }
@ -991,7 +1001,7 @@ mod tests {
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
payload.poll_stream().unwrap(); payload.poll_stream().unwrap();
assert_eq!(None, payload.read_max(1)); assert_eq!(None, payload.read_max(1).unwrap());
}) })
} }
@ -1001,14 +1011,14 @@ mod tests {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
assert_eq!(None, payload.read_max(4)); assert_eq!(None, payload.read_max(4).unwrap());
sender.feed_data(Bytes::from("data")); sender.feed_data(Bytes::from("data"));
sender.feed_eof(); sender.feed_eof();
payload.poll_stream().unwrap(); payload.poll_stream().unwrap();
assert_eq!(Some(Bytes::from("data")), payload.read_max(4)); assert_eq!(Some(Bytes::from("data")), payload.read_max(4).unwrap());
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
assert_eq!(None, payload.read_max(1)); assert!(payload.read_max(1).is_err());
assert!(payload.eof); assert!(payload.eof);
}) })
} }
@ -1018,7 +1028,7 @@ mod tests {
run_on(|| { run_on(|| {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
assert_eq!(None, payload.read_max(1)); assert_eq!(None, payload.read_max(1).unwrap());
sender.set_error(PayloadError::Incomplete(None)); sender.set_error(PayloadError::Incomplete(None));
payload.poll_stream().err().unwrap(); payload.poll_stream().err().unwrap();
}) })
@ -1035,10 +1045,10 @@ mod tests {
payload.poll_stream().unwrap(); payload.poll_stream().unwrap();
assert_eq!(payload.buf.len(), 10); assert_eq!(payload.buf.len(), 10);
assert_eq!(Some(Bytes::from("line1")), payload.read_max(5)); assert_eq!(Some(Bytes::from("line1")), payload.read_max(5).unwrap());
assert_eq!(payload.buf.len(), 5); assert_eq!(payload.buf.len(), 5);
assert_eq!(Some(Bytes::from("line2")), payload.read_max(5)); assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap());
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
}) })
} }
@ -1069,16 +1079,22 @@ mod tests {
let (mut sender, payload) = Payload::create(false); let (mut sender, payload) = Payload::create(false);
let mut payload = PayloadBuffer::new(payload); let mut payload = PayloadBuffer::new(payload);
assert_eq!(None, payload.read_until(b"ne")); assert_eq!(None, payload.read_until(b"ne").unwrap());
sender.feed_data(Bytes::from("line1")); sender.feed_data(Bytes::from("line1"));
sender.feed_data(Bytes::from("line2")); sender.feed_data(Bytes::from("line2"));
payload.poll_stream().unwrap(); payload.poll_stream().unwrap();
assert_eq!(Some(Bytes::from("line")), payload.read_until(b"ne")); assert_eq!(
Some(Bytes::from("line")),
payload.read_until(b"ne").unwrap()
);
assert_eq!(payload.buf.len(), 6); assert_eq!(payload.buf.len(), 6);
assert_eq!(Some(Bytes::from("1line2")), payload.read_until(b"2")); assert_eq!(
Some(Bytes::from("1line2")),
payload.read_until(b"2").unwrap()
);
assert_eq!(payload.buf.len(), 0); assert_eq!(payload.buf.len(), 0);
}) })
} }

View File

@ -1,5 +1,9 @@
# Changes # Changes
## [0.1.1] - 2019-06-03
* Fix optional cookie session support
## [0.1.0] - 2019-05-18 ## [0.1.0] - 2019-05-18
* Use actix-web 1.0.0-rc * Use actix-web 1.0.0-rc

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-session" name = "actix-session"
version = "0.1.0" version = "0.1.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Session for actix web framework." description = "Session for actix web framework."
readme = "README.md" readme = "README.md"
@ -24,12 +24,12 @@ default = ["cookie-session"]
cookie-session = ["actix-web/secure-cookies"] cookie-session = ["actix-web/secure-cookies"]
[dependencies] [dependencies]
actix-web = "1.0.0-rc" actix-web = "1.0.0"
actix-service = "0.4.0" actix-service = "0.4.1"
bytes = "0.4" bytes = "0.4"
derive_more = "0.14" derive_more = "0.15.0"
futures = "0.1.25" futures = "0.1.25"
hashbrown = "0.3.0" hashbrown = "0.5.0"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
time = "0.1.42" time = "0.1.42"

View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
actix-session/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -52,7 +52,9 @@ use serde::de::DeserializeOwned;
use serde::Serialize; use serde::Serialize;
use serde_json; use serde_json;
#[cfg(feature = "cookie-session")]
mod cookie; mod cookie;
#[cfg(feature = "cookie-session")]
pub use crate::cookie::CookieSession; pub use crate::cookie::CookieSession;
/// The high-level interface you use to modify session data. /// The high-level interface you use to modify session data.

View File

@ -1,5 +1,9 @@
# Changes # Changes
## [1.0.0] - 2019-05-29
* Update actix-http and actix-web
## [0.1.0-alpha.3] - 2019-04-02 ## [0.1.0-alpha.3] - 2019-04-02
* Update actix-http and actix-web * Update actix-http and actix-web

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-web-actors" name = "actix-web-actors"
version = "1.0.0-beta.4" version = "1.0.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix actors support for actix web framework." description = "Actix actors support for actix web framework."
readme = "README.md" readme = "README.md"
@ -18,9 +18,9 @@ name = "actix_web_actors"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix = "0.8.2" actix = "0.8.3"
actix-web = "1.0.0-beta.5" actix-web = "1.0.0"
actix-http = "0.2.0" actix-http = "0.2.4"
actix-codec = "0.1.2" actix-codec = "0.1.2"
bytes = "0.4" bytes = "0.4"
futures = "0.1.25" futures = "0.1.25"

View File

@ -0,0 +1 @@
../LICENSE-APACHE

View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -1,5 +1,13 @@
# Changes # Changes
## [0.1.2] - 2019-06-04
* Add macros for head, options, trace, connect and patch http methods
## [0.1.1] - 2019-06-01
* Add syn "extra-traits" feature
## [0.1.0] - 2019-05-18 ## [0.1.0] - 2019-05-18
* Release * Release

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-web-codegen" name = "actix-web-codegen"
version = "0.1.0" version = "0.1.2"
description = "Actix web proc macros" description = "Actix web proc macros"
readme = "README.md" readme = "README.md"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
@ -12,11 +12,11 @@ workspace = ".."
proc-macro = true proc-macro = true
[dependencies] [dependencies]
quote = "0.6" quote = "0.6.12"
syn = { version = "0.15", features = ["full", "parsing"] } syn = { version = "0.15.34", features = ["full", "parsing", "extra-traits"] }
[dev-dependencies] [dev-dependencies]
actix-web = { version = "1.0.0-beta.5" } actix-web = { version = "1.0.0" }
actix-http = { version = "0.2.0", features=["ssl"] } actix-http = { version = "0.2.4", features=["ssl"] }
actix-http-test = { version = "0.2.0", features=["ssl"] } actix-http-test = { version = "0.2.0", features=["ssl"] }
futures = { version = "0.1" } futures = { version = "0.1" }

View File

@ -0,0 +1 @@
../LICENSE-APACHE

View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -11,6 +11,11 @@
//! - [post](attr.post.html) //! - [post](attr.post.html)
//! - [put](attr.put.html) //! - [put](attr.put.html)
//! - [delete](attr.delete.html) //! - [delete](attr.delete.html)
//! - [head](attr.head.html)
//! - [connect](attr.connect.html)
//! - [options](attr.options.html)
//! - [trace](attr.trace.html)
//! - [patch](attr.patch.html)
//! //!
//! ### Attributes: //! ### Attributes:
//! //!
@ -92,3 +97,63 @@ pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
let gen = route::Args::new(&args, input, route::GuardType::Delete); let gen = route::Args::new(&args, input, route::GuardType::Delete);
gen.generate() gen.generate()
} }
/// Creates route handler with `HEAD` method guard.
///
/// Syntax: `#[head("path"[, attributes])]`
///
/// Attributes are the same as in [head](attr.head.html)
#[proc_macro_attribute]
pub fn head(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as syn::AttributeArgs);
let gen = route::Args::new(&args, input, route::GuardType::Head);
gen.generate()
}
/// Creates route handler with `CONNECT` method guard.
///
/// Syntax: `#[connect("path"[, attributes])]`
///
/// Attributes are the same as in [connect](attr.connect.html)
#[proc_macro_attribute]
pub fn connect(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as syn::AttributeArgs);
let gen = route::Args::new(&args, input, route::GuardType::Connect);
gen.generate()
}
/// Creates route handler with `OPTIONS` method guard.
///
/// Syntax: `#[options("path"[, attributes])]`
///
/// Attributes are the same as in [options](attr.options.html)
#[proc_macro_attribute]
pub fn options(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as syn::AttributeArgs);
let gen = route::Args::new(&args, input, route::GuardType::Options);
gen.generate()
}
/// Creates route handler with `TRACE` method guard.
///
/// Syntax: `#[trace("path"[, attributes])]`
///
/// Attributes are the same as in [trace](attr.trace.html)
#[proc_macro_attribute]
pub fn trace(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as syn::AttributeArgs);
let gen = route::Args::new(&args, input, route::GuardType::Trace);
gen.generate()
}
/// Creates route handler with `PATCH` method guard.
///
/// Syntax: `#[patch("path"[, attributes])]`
///
/// Attributes are the same as in [patch](attr.patch.html)
#[proc_macro_attribute]
pub fn patch(args: TokenStream, input: TokenStream) -> TokenStream {
let args = parse_macro_input!(args as syn::AttributeArgs);
let gen = route::Args::new(&args, input, route::GuardType::Patch);
gen.generate()
}

View File

@ -25,6 +25,11 @@ pub enum GuardType {
Post, Post,
Put, Put,
Delete, Delete,
Head,
Connect,
Options,
Trace,
Patch,
} }
impl fmt::Display for GuardType { impl fmt::Display for GuardType {
@ -34,6 +39,11 @@ impl fmt::Display for GuardType {
&GuardType::Post => write!(f, "Post"), &GuardType::Post => write!(f, "Post"),
&GuardType::Put => write!(f, "Put"), &GuardType::Put => write!(f, "Put"),
&GuardType::Delete => write!(f, "Delete"), &GuardType::Delete => write!(f, "Delete"),
&GuardType::Head => write!(f, "Head"),
&GuardType::Connect => write!(f, "Connect"),
&GuardType::Options => write!(f, "Options"),
&GuardType::Trace => write!(f, "Trace"),
&GuardType::Patch => write!(f, "Patch"),
} }
} }
} }

View File

@ -1,7 +1,7 @@
use actix_http::HttpService; use actix_http::HttpService;
use actix_http_test::TestServer; use actix_http_test::TestServer;
use actix_web::{http, web::Path, App, HttpResponse, Responder}; use actix_web::{http, web::Path, App, HttpResponse, Responder};
use actix_web_codegen::{delete, get, post, put}; use actix_web_codegen::{connect, delete, get, head, options, patch, post, put, trace};
use futures::{future, Future}; use futures::{future, Future};
#[get("/test")] #[get("/test")]
@ -14,11 +14,36 @@ fn put_test() -> impl Responder {
HttpResponse::Created() HttpResponse::Created()
} }
#[patch("/test")]
fn patch_test() -> impl Responder {
HttpResponse::Ok()
}
#[post("/test")] #[post("/test")]
fn post_test() -> impl Responder { fn post_test() -> impl Responder {
HttpResponse::NoContent() HttpResponse::NoContent()
} }
#[head("/test")]
fn head_test() -> impl Responder {
HttpResponse::Ok()
}
#[connect("/test")]
fn connect_test() -> impl Responder {
HttpResponse::Ok()
}
#[options("/test")]
fn options_test() -> impl Responder {
HttpResponse::Ok()
}
#[trace("/test")]
fn trace_test() -> impl Responder {
HttpResponse::Ok()
}
#[get("/test")] #[get("/test")]
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> { fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
future::ok(HttpResponse::Ok().finish()) future::ok(HttpResponse::Ok().finish())
@ -75,6 +100,11 @@ fn test_body() {
App::new() App::new()
.service(post_test) .service(post_test)
.service(put_test) .service(put_test)
.service(head_test)
.service(connect_test)
.service(options_test)
.service(trace_test)
.service(patch_test)
.service(test), .service(test),
) )
}); });
@ -82,6 +112,26 @@ fn test_body() {
let response = srv.block_on(request.send()).unwrap(); let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
let request = srv.request(http::Method::HEAD, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::CONNECT, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::OPTIONS, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::TRACE, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::PATCH, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::PUT, srv.url("/test")); let request = srv.request(http::Method::PUT, srv.url("/test"));
let response = srv.block_on(request.send()).unwrap(); let response = srv.block_on(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());

View File

@ -1,5 +1,11 @@
# Changes # Changes
## [0.2.1] - 2019-06-05
### Added
* Add license files
## [0.2.0] - 2019-05-12 ## [0.2.0] - 2019-05-12
### Added ### Added

View File

@ -1,6 +1,6 @@
[package] [package]
name = "awc" name = "awc"
version = "0.2.0" version = "0.2.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http client." description = "Actix http client."
readme = "README.md" readme = "README.md"
@ -40,11 +40,11 @@ flate2-rust = ["actix-http/flate2-rust"]
[dependencies] [dependencies]
actix-codec = "0.1.2" actix-codec = "0.1.2"
actix-service = "0.4.0" actix-service = "0.4.1"
actix-http = "0.2.0" actix-http = "0.2.4"
base64 = "0.10.1" base64 = "0.10.1"
bytes = "0.4" bytes = "0.4"
derive_more = "0.14" derive_more = "0.15.0"
futures = "0.1.25" futures = "0.1.25"
log =" 0.4" log =" 0.4"
mime = "0.3" mime = "0.3"
@ -58,11 +58,11 @@ openssl = { version="0.10", optional = true }
[dev-dependencies] [dev-dependencies]
actix-rt = "0.2.2" actix-rt = "0.2.2"
actix-web = { version = "1.0.0-beta.4", features=["ssl"] } actix-web = { version = "1.0.0", features=["ssl"] }
actix-http = { version = "0.2.0", features=["ssl"] } actix-http = { version = "0.2.4", features=["ssl"] }
actix-http-test = { version = "0.2.0", features=["ssl"] } actix-http-test = { version = "0.2.0", features=["ssl"] }
actix-utils = "0.4.0" actix-utils = "0.4.1"
actix-server = { version = "0.5.0", features=["ssl"] } actix-server = { version = "0.5.1", features=["ssl"] }
brotli2 = { version="0.3.2" } brotli2 = { version="0.3.2" }
flate2 = { version="1.0.2" } flate2 = { version="1.0.2" }
env_logger = "0.6" env_logger = "0.6"

1
awc/LICENSE-APACHE Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
awc/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -38,6 +38,7 @@ pub mod test;
pub mod ws; pub mod ws;
pub use self::builder::ClientBuilder; pub use self::builder::ClientBuilder;
pub use self::connect::BoxedSocket;
pub use self::request::ClientRequest; pub use self::request::ClientRequest;
pub use self::response::{ClientResponse, JsonBody, MessageBody}; pub use self::response::{ClientResponse, JsonBody, MessageBody};

View File

@ -100,6 +100,13 @@ where
self 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));
self
}
/// Run external configuration as part of the application building /// Run external configuration as part of the application building
/// process /// process
/// ///
@ -218,7 +225,6 @@ where
/// It is also possible to use static files as default service. /// It is also possible to use static files as default service.
/// ///
/// ```rust /// ```rust
/// use actix_files::Files;
/// use actix_web::{web, App, HttpResponse}; /// use actix_web::{web, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
@ -226,7 +232,7 @@ where
/// .service( /// .service(
/// web::resource("/index.html").to(|| HttpResponse::Ok())) /// web::resource("/index.html").to(|| HttpResponse::Ok()))
/// .default_service( /// .default_service(
/// Files::new("", "./static") /// web::to(|| HttpResponse::NotFound())
/// ); /// );
/// } /// }
/// ``` /// ```

View File

@ -183,7 +183,7 @@ where
} }
/// Service to convert `Request` to a `ServiceRequest<S>` /// Service to convert `Request` to a `ServiceRequest<S>`
pub struct AppInitService<T: Service, B> pub struct AppInitService<T, B>
where where
T: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>, T: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{ {
@ -215,19 +215,30 @@ where
inner.path.get_mut().update(&head.uri); inner.path.get_mut().update(&head.uri);
inner.path.reset(); inner.path.reset();
inner.head = head; inner.head = head;
inner.payload = payload;
inner.app_data = self.data.clone(); inner.app_data = self.data.clone();
req req
} else { } else {
HttpRequest::new( HttpRequest::new(
Path::new(Url::new(head.uri.clone())), Path::new(Url::new(head.uri.clone())),
head, head,
payload,
self.rmap.clone(), self.rmap.clone(),
self.config.clone(), self.config.clone(),
self.data.clone(), self.data.clone(),
self.pool, self.pool,
) )
}; };
self.service.call(ServiceRequest::from_parts(req, payload)) self.service.call(ServiceRequest::new(req))
}
}
impl<T, B> Drop for AppInitService<T, B>
where
T: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
fn drop(&mut self) {
self.pool.clear();
} }
} }
@ -408,3 +419,37 @@ impl NewService for AppEntry {
self.factory.borrow_mut().as_mut().unwrap().new_service(&()) self.factory.borrow_mut().as_mut().unwrap().new_service(&())
} }
} }
#[cfg(test)]
mod tests {
use actix_service::Service;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use crate::{test, web, App, HttpResponse};
struct DropData(Arc<AtomicBool>);
impl Drop for DropData {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
#[test]
fn drop_data() {
let data = Arc::new(AtomicBool::new(false));
{
let mut app = test::init_service(
App::new()
.data(DropData(data.clone()))
.service(web::resource("/test").to(|| HttpResponse::Ok())),
);
let req = test::TestRequest::with_uri("/test").to_request();
let _ = test::block_on(app.call(req)).unwrap();
}
assert!(data.load(Ordering::Relaxed));
}
}

View File

@ -188,7 +188,7 @@ impl ServiceConfig {
} }
} }
/// Set application data. Applicatin data could be accessed /// Set application data. Application data could be accessed
/// by using `Data<T>` extractor where `T` is data type. /// by using `Data<T>` extractor where `T` is data type.
/// ///
/// This is same as `App::data()` method. /// This is same as `App::data()` method.

View File

@ -54,7 +54,7 @@ pub(crate) trait DataFactory {
/// ///
/// let app = App::new() /// let app = App::new()
/// // Store `MyData` in application storage. /// // Store `MyData` in application storage.
/// .data(data.clone()) /// .register_data(data.clone())
/// .service( /// .service(
/// web::resource("/index.html").route( /// web::resource("/index.html").route(
/// web::get().to(index))); /// web::get().to(index)));
@ -130,6 +130,7 @@ impl<T: 'static> DataFactory for Data<T> {
mod tests { mod tests {
use actix_service::Service; use actix_service::Service;
use super::*;
use crate::http::StatusCode; use crate::http::StatusCode;
use crate::test::{block_on, init_service, TestRequest}; use crate::test::{block_on, init_service, TestRequest};
use crate::{web, App, HttpResponse}; use crate::{web, App, HttpResponse};
@ -154,6 +155,26 @@ mod tests {
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
} }
#[test]
fn test_register_data_extractor() {
let mut srv =
init_service(App::new().register_data(Data::new(10usize)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let mut srv =
init_service(App::new().register_data(Data::new(10u32)).service(
web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok()),
));
let req = TestRequest::default().to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test] #[test]
fn test_route_data_extractor() { fn test_route_data_extractor() {
let mut srv = let mut srv =

View File

@ -92,6 +92,23 @@ impl ResponseError for JsonPayloadError {
} }
} }
/// A set of errors that can occur during parsing request paths
#[derive(Debug, Display, From)]
pub enum PathError {
/// Deserialize error
#[display(fmt = "Path deserialize error: {}", _0)]
Deserialize(de::Error),
}
/// Return `BadRequest` for `PathError`
impl ResponseError for PathError {
fn error_response(&self) -> HttpResponse {
match *self {
PathError::Deserialize(_) => HttpResponse::new(StatusCode::BAD_REQUEST),
}
}
}
/// A set of errors that can occur during parsing query strings /// A set of errors that can occur during parsing query strings
#[derive(Debug, Display, From)] #[derive(Debug, Display, From)]
pub enum QueryPayloadError { pub enum QueryPayloadError {

View File

@ -1,7 +1,7 @@
use std::convert::Infallible; use std::convert::Infallible;
use std::marker::PhantomData; use std::marker::PhantomData;
use actix_http::{Error, Payload, Response}; use actix_http::{Error, Response};
use actix_service::{NewService, Service}; use actix_service::{NewService, Service};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{try_ready, Async, Future, IntoFuture, Poll}; use futures::{try_ready, Async, Future, IntoFuture, Poll};
@ -331,15 +331,15 @@ where
ExtractResponse { ExtractResponse {
fut, fut,
req,
fut_s: None, fut_s: None,
req: Some((req, payload)),
service: self.service.clone(), service: self.service.clone(),
} }
} }
} }
pub struct ExtractResponse<T: FromRequest, S: Service> { pub struct ExtractResponse<T: FromRequest, S: Service> {
req: Option<(HttpRequest, Payload)>, req: HttpRequest,
service: S, service: S,
fut: <T::Future as IntoFuture>::Future, fut: <T::Future as IntoFuture>::Future,
fut_s: Option<S::Future>, fut_s: Option<S::Future>,
@ -362,12 +362,11 @@ where
} }
let item = try_ready!(self.fut.poll().map_err(|e| { let item = try_ready!(self.fut.poll().map_err(|e| {
let (req, payload) = self.req.take().unwrap(); let req = ServiceRequest::new(self.req.clone());
let req = ServiceRequest::from_parts(req, payload);
(e.into(), req) (e.into(), req)
})); }));
self.fut_s = Some(self.service.call((item, self.req.take().unwrap().0))); self.fut_s = Some(self.service.call((item, self.req.clone())));
self.poll() self.poll()
} }
} }

View File

@ -66,15 +66,15 @@
//! //!
//! ## Package feature //! ## Package feature
//! //!
//! * `client` - enables http client //! * `client` - enables http client (default enabled)
//! * `ssl` - enables ssl support via `openssl` crate, supports `http/2` //! * `ssl` - enables ssl support via `openssl` crate, supports `http/2`
//! * `rust-tls` - enables ssl support via `rustls` crate, supports `http/2` //! * `rust-tls` - enables ssl support via `rustls` crate, supports `http/2`
//! * `secure-cookies` - enables secure cookies support, includes `ring` crate as //! * `secure-cookies` - enables secure cookies support, includes `ring` crate as
//! dependency //! dependency
//! * `brotli` - enables `brotli` compression support, requires `c` //! * `brotli` - enables `brotli` compression support, requires `c`
//! compiler //! compiler (default enabled)
//! * `flate2-zlib` - enables `gzip`, `deflate` compression support, requires //! * `flate2-zlib` - enables `gzip`, `deflate` compression support, requires
//! `c` compiler //! `c` compiler (default enabled)
//! * `flate2-rust` - experimental rust based implementation for //! * `flate2-rust` - experimental rust based implementation for
//! `gzip`, `deflate` compression. //! `gzip`, `deflate` compression.
//! //!
@ -111,7 +111,7 @@ pub use actix_web_codegen::*;
// re-export for convenience // re-export for convenience
pub use actix_http::Response as HttpResponse; pub use actix_http::Response as HttpResponse;
pub use actix_http::{cookie, http, Error, HttpMessage, ResponseError, Result}; pub use actix_http::{body, cookie, http, Error, HttpMessage, ResponseError, Result};
pub use crate::app::App; pub use crate::app::App;
pub use crate::extract::FromRequest; pub use crate::extract::FromRequest;
@ -143,7 +143,7 @@ pub mod dev {
pub use crate::types::json::JsonBody; pub use crate::types::json::JsonBody;
pub use crate::types::readlines::Readlines; pub use crate::types::readlines::Readlines;
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody}; pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
pub use actix_http::encoding::Decoder as Decompress; pub use actix_http::encoding::Decoder as Decompress;
pub use actix_http::ResponseBuilder as HttpResponseBuilder; pub use actix_http::ResponseBuilder as HttpResponseBuilder;
pub use actix_http::{ pub use actix_http::{
@ -151,6 +151,7 @@ pub mod dev {
}; };
pub use actix_router::{Path, ResourceDef, ResourcePath, Url}; pub use actix_router::{Path, ResourceDef, ResourcePath, Url};
pub use actix_server::Server; pub use actix_server::Server;
pub use actix_service::{Service, Transform};
pub(crate) fn insert_slash(path: &str) -> String { pub(crate) fn insert_slash(path: &str) -> String {
let mut path = path.to_owned(); let mut path = path.to_owned();

View File

@ -53,7 +53,7 @@ use crate::HttpResponse;
/// ///
/// `%a` Remote IP-address (IP-address of proxy if using reverse proxy) /// `%a` Remote IP-address (IP-address of proxy if using reverse proxy)
/// ///
/// `%t` Time when the request was started to process /// `%t` Time when the request was started to process (in rfc3339 format)
/// ///
/// `%r` First line of request /// `%r` First line of request
/// ///
@ -417,10 +417,7 @@ impl FormatText {
} }
FormatText::UrlPath => *self = FormatText::Str(format!("{}", req.path())), FormatText::UrlPath => *self = FormatText::Str(format!("{}", req.path())),
FormatText::RequestTime => { FormatText::RequestTime => {
*self = FormatText::Str(format!( *self = FormatText::Str(format!("{}", now.rfc3339()))
"{:?}",
now.strftime("[%d/%b/%Y:%H:%M:%S %z]").unwrap()
))
} }
FormatText::RequestHeader(ref name) => { FormatText::RequestHeader(ref name) => {
let s = if let Some(val) = req.headers().get(name) { let s = if let Some(val) = req.headers().get(name) {
@ -547,4 +544,29 @@ mod tests {
assert!(s.contains("200 1024")); assert!(s.contains("200 1024"));
assert!(s.contains("ACTIX-WEB")); assert!(s.contains("ACTIX-WEB"));
} }
#[test]
fn test_request_time_format() {
let mut format = Format::new("%t");
let req = TestRequest::default().to_srv_request();
let now = time::now();
for unit in &mut format.0 {
unit.render_request(now, &req);
}
let resp = HttpResponse::build(StatusCode::OK).force_close().finish();
for unit in &mut format.0 {
unit.render_response(&resp);
}
let render = |fmt: &mut Formatter| {
for unit in &format.0 {
unit.render(fmt, 1024, now)?;
}
Ok(())
};
let s = format!("{}", FormatDisplay(&render));
assert!(s.contains(&format!("{}", now.rfc3339())));
}
} }

View File

@ -2,7 +2,6 @@
mod compress; mod compress;
pub use self::compress::{BodyEncoding, Compress}; pub use self::compress::{BodyEncoding, Compress};
pub mod cors;
mod defaultheaders; mod defaultheaders;
pub mod errhandlers; pub mod errhandlers;
mod logger; mod logger;
@ -12,5 +11,16 @@ pub use self::defaultheaders::DefaultHeaders;
pub use self::logger::Logger; pub use self::logger::Logger;
pub use self::normalize::NormalizePath; pub use self::normalize::NormalizePath;
#[cfg(feature = "secure-cookies")] #[cfg(feature = "deprecated")]
pub mod identity; #[deprecated(
since = "1.0.1",
note = "please use `actix_cors` instead. support will be removed in actix-web 1.0.2"
)]
pub use actix_cors as cors;
#[cfg(feature = "deprecated")]
#[deprecated(
since = "1.0.1",
note = "please use `actix_identity` instead. support will be removed in actix-web 1.0.2"
)]
pub use actix_identity as identity;

View File

@ -20,6 +20,7 @@ pub struct HttpRequest(pub(crate) Rc<HttpRequestInner>);
pub(crate) struct HttpRequestInner { pub(crate) struct HttpRequestInner {
pub(crate) head: Message<RequestHead>, pub(crate) head: Message<RequestHead>,
pub(crate) path: Path<Url>, pub(crate) path: Path<Url>,
pub(crate) payload: Payload,
pub(crate) app_data: Rc<Extensions>, pub(crate) app_data: Rc<Extensions>,
rmap: Rc<ResourceMap>, rmap: Rc<ResourceMap>,
config: AppConfig, config: AppConfig,
@ -31,6 +32,7 @@ impl HttpRequest {
pub(crate) fn new( pub(crate) fn new(
path: Path<Url>, path: Path<Url>,
head: Message<RequestHead>, head: Message<RequestHead>,
payload: Payload,
rmap: Rc<ResourceMap>, rmap: Rc<ResourceMap>,
config: AppConfig, config: AppConfig,
app_data: Rc<Extensions>, app_data: Rc<Extensions>,
@ -39,6 +41,7 @@ impl HttpRequest {
HttpRequest(Rc::new(HttpRequestInner { HttpRequest(Rc::new(HttpRequestInner {
head, head,
path, path,
payload,
rmap, rmap,
config, config,
app_data, app_data,
@ -325,6 +328,10 @@ impl HttpRequestPool {
None None
} }
} }
pub(crate) fn clear(&self) {
self.0.borrow_mut().clear()
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -38,7 +38,8 @@ impl ResourceMap {
pub(crate) fn finish(&self, current: Rc<ResourceMap>) { pub(crate) fn finish(&self, current: Rc<ResourceMap>) {
for (_, nested) in &self.patterns { for (_, nested) in &self.patterns {
if let Some(ref nested) = nested { if let Some(ref nested) = nested {
*nested.parent.borrow_mut() = Some(current.clone()) *nested.parent.borrow_mut() = Some(current.clone());
nested.finish(nested.clone());
} }
} }
} }
@ -122,7 +123,9 @@ impl ResourceMap {
I: AsRef<str>, I: AsRef<str>,
{ {
if let Some(pattern) = self.named.get(name) { if let Some(pattern) = self.named.get(name) {
self.fill_root(path, elements)?; if pattern.pattern().starts_with("/") {
self.fill_root(path, elements)?;
}
if pattern.resource_path(path, elements) { if pattern.resource_path(path, elements) {
Ok(Some(())) Ok(Some(()))
} else { } else {

View File

@ -11,6 +11,7 @@ use actix_service::{
use futures::future::{ok, Either, Future, FutureResult}; use futures::future::{ok, Either, Future, FutureResult};
use futures::{Async, IntoFuture, Poll}; use futures::{Async, IntoFuture, Poll};
use crate::config::ServiceConfig;
use crate::data::Data; use crate::data::Data;
use crate::dev::{AppService, HttpServiceFactory}; use crate::dev::{AppService, HttpServiceFactory};
use crate::error::Error; use crate::error::Error;
@ -66,6 +67,7 @@ pub struct Scope<T = ScopeEndpoint> {
services: Vec<Box<ServiceFactory>>, services: Vec<Box<ServiceFactory>>,
guards: Vec<Box<Guard>>, guards: Vec<Box<Guard>>,
default: Rc<RefCell<Option<Rc<HttpNewService>>>>, default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
external: Vec<ResourceDef>,
factory_ref: Rc<RefCell<Option<ScopeFactory>>>, factory_ref: Rc<RefCell<Option<ScopeFactory>>>,
} }
@ -80,6 +82,7 @@ impl Scope {
guards: Vec::new(), guards: Vec::new(),
services: Vec::new(), services: Vec::new(),
default: Rc::new(RefCell::new(None)), default: Rc::new(RefCell::new(None)),
external: Vec::new(),
factory_ref: fref, factory_ref: fref,
} }
} }
@ -153,6 +156,56 @@ where
self self
} }
/// Run external configuration as part of the scope building
/// process
///
/// This function is useful for moving parts of configuration to a
/// different module or even library. For example,
/// some of the resource's configuration could be moved to different module.
///
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{web, middleware, App, HttpResponse};
///
/// // this function could be located in different module
/// fn config(cfg: &mut web::ServiceConfig) {
/// cfg.service(web::resource("/test")
/// .route(web::get().to(|| HttpResponse::Ok()))
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// );
/// }
///
/// fn main() {
/// let app = App::new()
/// .wrap(middleware::Logger::default())
/// .service(
/// web::scope("/api")
/// .configure(config)
/// )
/// .route("/index.html", web::get().to(|| HttpResponse::Ok()));
/// }
/// ```
pub fn configure<F>(mut self, f: F) -> Self
where
F: FnOnce(&mut ServiceConfig),
{
let mut cfg = ServiceConfig::new();
f(&mut cfg);
self.services.extend(cfg.services);
self.external.extend(cfg.external);
if !cfg.data.is_empty() {
let mut data = self.data.unwrap_or_else(|| Extensions::new());
for value in cfg.data.iter() {
value.create(&mut data);
}
self.data = Some(data);
}
self
}
/// Register http service. /// Register http service.
/// ///
/// This is similar to `App's` service registration. /// This is similar to `App's` service registration.
@ -281,6 +334,7 @@ where
guards: self.guards, guards: self.guards,
services: self.services, services: self.services,
default: self.default, default: self.default,
external: self.external,
factory_ref: self.factory_ref, factory_ref: self.factory_ref,
} }
} }
@ -359,6 +413,11 @@ where
let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef)); let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef));
// external resources
for mut rdef in std::mem::replace(&mut self.external, Vec::new()) {
rmap.add(&mut rdef, None);
}
// custom app data storage // custom app data storage
if let Some(ref mut ext) = self.data { if let Some(ref mut ext) = self.data {
config.set_service_data(ext); config.set_service_data(ext);
@ -594,7 +653,7 @@ mod tests {
use crate::dev::{Body, ResponseBody}; use crate::dev::{Body, ResponseBody};
use crate::http::{header, HeaderValue, Method, StatusCode}; use crate::http::{header, HeaderValue, Method, StatusCode};
use crate::service::{ServiceRequest, ServiceResponse}; use crate::service::{ServiceRequest, ServiceResponse};
use crate::test::{block_on, call_service, init_service, TestRequest}; use crate::test::{block_on, call_service, init_service, read_body, TestRequest};
use crate::{guard, web, App, Error, HttpRequest, HttpResponse}; use crate::{guard, web, App, Error, HttpRequest, HttpResponse};
#[test] #[test]
@ -1022,4 +1081,78 @@ mod tests {
let resp = call_service(&mut srv, req); let resp = call_service(&mut srv, req);
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
#[test]
fn test_scope_config() {
let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| {
s.route("/path1", web::get().to(|| HttpResponse::Ok()));
})));
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[test]
fn test_scope_config_2() {
let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| {
s.service(web::scope("/v1").configure(|s| {
s.route("/", web::get().to(|| HttpResponse::Ok()));
}));
})));
let req = TestRequest::with_uri("/app/v1/").to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[test]
fn test_url_for_external() {
let mut srv =
init_service(App::new().service(web::scope("/app").configure(|s| {
s.service(web::scope("/v1").configure(|s| {
s.external_resource(
"youtube",
"https://youtube.com/watch/{video_id}",
);
s.route(
"/",
web::get().to(|req: HttpRequest| {
HttpResponse::Ok().body(format!(
"{}",
req.url_for("youtube", &["xxxxxx"]).unwrap().as_str()
))
}),
);
}));
})));
let req = TestRequest::with_uri("/app/v1/").to_request();
let resp = block_on(srv.call(req)).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp);
assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]);
}
#[test]
fn test_url_for_nested() {
let mut srv = init_service(App::new().service(web::scope("/a").service(
web::scope("/b").service(web::resource("/c/{stuff}").name("c").route(
web::get().to(|req: HttpRequest| {
HttpResponse::Ok()
.body(format!("{}", req.url_for("c", &["12345"]).unwrap()))
}),
)),
)));
let req = TestRequest::with_uri("/a/b/c/test").to_request();
let resp = call_service(&mut srv, req);
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp);
assert_eq!(
body,
Bytes::from_static(b"http://localhost:8080/a/b/c/12345")
);
}
} }

View File

@ -64,7 +64,7 @@ where
config: Arc<Mutex<Config>>, config: Arc<Mutex<Config>>,
backlog: i32, backlog: i32,
sockets: Vec<Socket>, sockets: Vec<Socket>,
builder: Option<ServerBuilder>, builder: ServerBuilder,
_t: PhantomData<(S, B)>, _t: PhantomData<(S, B)>,
} }
@ -91,7 +91,7 @@ where
})), })),
backlog: 1024, backlog: 1024,
sockets: Vec::new(), sockets: Vec::new(),
builder: Some(ServerBuilder::default()), builder: ServerBuilder::default(),
_t: PhantomData, _t: PhantomData,
} }
} }
@ -101,7 +101,7 @@ where
/// By default http server uses number of available logical cpu as threads /// By default http server uses number of available logical cpu as threads
/// count. /// count.
pub fn workers(mut self, num: usize) -> Self { pub fn workers(mut self, num: usize) -> Self {
self.builder = Some(self.builder.take().unwrap().workers(num)); self.builder = self.builder.workers(num);
self self
} }
@ -117,7 +117,7 @@ where
/// This method should be called before `bind()` method call. /// This method should be called before `bind()` method call.
pub fn backlog(mut self, backlog: i32) -> Self { pub fn backlog(mut self, backlog: i32) -> Self {
self.backlog = backlog; self.backlog = backlog;
self.builder = Some(self.builder.take().unwrap().backlog(backlog)); self.builder = self.builder.backlog(backlog);
self self
} }
@ -128,7 +128,7 @@ where
/// ///
/// By default max connections is set to a 25k. /// By default max connections is set to a 25k.
pub fn maxconn(mut self, num: usize) -> Self { pub fn maxconn(mut self, num: usize) -> Self {
self.builder = Some(self.builder.take().unwrap().maxconn(num)); self.builder = self.builder.maxconn(num);
self self
} }
@ -139,7 +139,7 @@ where
/// ///
/// By default max connections is set to a 256. /// By default max connections is set to a 256.
pub fn maxconnrate(mut self, num: usize) -> Self { pub fn maxconnrate(mut self, num: usize) -> Self {
self.builder = Some(self.builder.take().unwrap().maxconnrate(num)); self.builder = self.builder.maxconnrate(num);
self self
} }
@ -190,13 +190,13 @@ where
/// Stop actix system. /// Stop actix system.
pub fn system_exit(mut self) -> Self { pub fn system_exit(mut self) -> Self {
self.builder = Some(self.builder.take().unwrap().system_exit()); self.builder = self.builder.system_exit();
self self
} }
/// Disable signal handling /// Disable signal handling
pub fn disable_signals(mut self) -> Self { pub fn disable_signals(mut self) -> Self {
self.builder = Some(self.builder.take().unwrap().disable_signals()); self.builder = self.builder.disable_signals();
self self
} }
@ -208,7 +208,7 @@ where
/// ///
/// By default shutdown timeout sets to 30 seconds. /// By default shutdown timeout sets to 30 seconds.
pub fn shutdown_timeout(mut self, sec: u64) -> Self { pub fn shutdown_timeout(mut self, sec: u64) -> Self {
self.builder = Some(self.builder.take().unwrap().shutdown_timeout(sec)); self.builder = self.builder.shutdown_timeout(sec);
self self
} }
@ -240,7 +240,7 @@ where
scheme: "http", scheme: "http",
}); });
self.builder = Some(self.builder.take().unwrap().listen( self.builder = self.builder.listen(
format!("actix-web-service-{}", addr), format!("actix-web-service-{}", addr),
lst, lst,
move || { move || {
@ -250,8 +250,7 @@ where
.client_timeout(c.client_timeout) .client_timeout(c.client_timeout)
.finish(factory()) .finish(factory())
}, },
)?); )?;
Ok(self) Ok(self)
} }
@ -260,20 +259,19 @@ where
/// ///
/// This method sets alpn protocols to "h2" and "http/1.1" /// This method sets alpn protocols to "h2" and "http/1.1"
pub fn listen_ssl( pub fn listen_ssl(
mut self, self,
lst: net::TcpListener, lst: net::TcpListener,
builder: SslAcceptorBuilder, builder: SslAcceptorBuilder,
) -> io::Result<Self> { ) -> io::Result<Self> {
self.listen_ssl_inner(lst, openssl_acceptor(builder)?)?; self.listen_ssl_inner(lst, openssl_acceptor(builder)?)
Ok(self)
} }
#[cfg(feature = "ssl")] #[cfg(feature = "ssl")]
fn listen_ssl_inner( fn listen_ssl_inner(
&mut self, mut self,
lst: net::TcpListener, lst: net::TcpListener,
acceptor: SslAcceptor, acceptor: SslAcceptor,
) -> io::Result<()> { ) -> io::Result<Self> {
use actix_server::ssl::{OpensslAcceptor, SslError}; use actix_server::ssl::{OpensslAcceptor, SslError};
let acceptor = OpensslAcceptor::new(acceptor); let acceptor = OpensslAcceptor::new(acceptor);
@ -285,7 +283,7 @@ where
scheme: "https", scheme: "https",
}); });
self.builder = Some(self.builder.take().unwrap().listen( self.builder = self.builder.listen(
format!("actix-web-service-{}", addr), format!("actix-web-service-{}", addr),
lst, lst,
move || { move || {
@ -300,8 +298,8 @@ where
.map_init_err(|_| ()), .map_init_err(|_| ()),
) )
}, },
)?); )?;
Ok(()) Ok(self)
} }
#[cfg(feature = "rust-tls")] #[cfg(feature = "rust-tls")]
@ -309,20 +307,19 @@ where
/// ///
/// This method sets alpn protocols to "h2" and "http/1.1" /// This method sets alpn protocols to "h2" and "http/1.1"
pub fn listen_rustls( pub fn listen_rustls(
mut self, self,
lst: net::TcpListener, lst: net::TcpListener,
config: RustlsServerConfig, config: RustlsServerConfig,
) -> io::Result<Self> { ) -> io::Result<Self> {
self.listen_rustls_inner(lst, config)?; self.listen_rustls_inner(lst, config)
Ok(self)
} }
#[cfg(feature = "rust-tls")] #[cfg(feature = "rust-tls")]
fn listen_rustls_inner( fn listen_rustls_inner(
&mut self, mut self,
lst: net::TcpListener, lst: net::TcpListener,
mut config: RustlsServerConfig, mut config: RustlsServerConfig,
) -> io::Result<()> { ) -> io::Result<Self> {
use actix_server::ssl::{RustlsAcceptor, SslError}; use actix_server::ssl::{RustlsAcceptor, SslError};
let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()]; let protos = vec!["h2".to_string().into(), "http/1.1".to_string().into()];
@ -337,7 +334,7 @@ where
scheme: "https", scheme: "https",
}); });
self.builder = Some(self.builder.take().unwrap().listen( self.builder = self.builder.listen(
format!("actix-web-service-{}", addr), format!("actix-web-service-{}", addr),
lst, lst,
move || { move || {
@ -352,8 +349,8 @@ where
.map_init_err(|_| ()), .map_init_err(|_| ()),
) )
}, },
)?); )?;
Ok(()) Ok(self)
} }
/// The socket address to bind /// The socket address to bind
@ -416,7 +413,7 @@ where
let acceptor = openssl_acceptor(builder)?; let acceptor = openssl_acceptor(builder)?;
for lst in sockets { for lst in sockets {
self.listen_ssl_inner(lst, acceptor.clone())?; self = self.listen_ssl_inner(lst, acceptor.clone())?;
} }
Ok(self) Ok(self)
@ -433,7 +430,7 @@ where
) -> io::Result<Self> { ) -> io::Result<Self> {
let sockets = self.bind2(addr)?; let sockets = self.bind2(addr)?;
for lst in sockets { for lst in sockets {
self.listen_rustls_inner(lst, config.clone())?; self = self.listen_rustls_inner(lst, config.clone())?;
} }
Ok(self) Ok(self)
} }
@ -473,8 +470,8 @@ where
/// sys.run() // <- Run actix system, this method starts all async processes /// sys.run() // <- Run actix system, this method starts all async processes
/// } /// }
/// ``` /// ```
pub fn start(mut self) -> Server { pub fn start(self) -> Server {
self.builder.take().unwrap().start() self.builder.start()
} }
/// Spawn new thread and start listening for incoming connections. /// Spawn new thread and start listening for incoming connections.

View File

@ -50,45 +50,46 @@ where
} }
} }
pub struct ServiceRequest { /// An service http request
req: HttpRequest, ///
payload: Payload, /// ServiceRequest allows mutable access to request's internal structures
} pub struct ServiceRequest(HttpRequest);
impl ServiceRequest { impl ServiceRequest {
/// Construct service request from parts /// Construct service request
pub(crate) fn from_parts(req: HttpRequest, payload: Payload) -> Self { pub(crate) fn new(req: HttpRequest) -> Self {
ServiceRequest { req, payload } ServiceRequest(req)
} }
/// Deconstruct request into parts /// Deconstruct request into parts
pub fn into_parts(self) -> (HttpRequest, Payload) { pub fn into_parts(mut self) -> (HttpRequest, Payload) {
(self.req, self.payload) let pl = Rc::get_mut(&mut (self.0).0).unwrap().payload.take();
(self.0, pl)
} }
/// Create service response /// Create service response
#[inline] #[inline]
pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> { pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> {
ServiceResponse::new(self.req, res.into()) ServiceResponse::new(self.0, res.into())
} }
/// Create service response for error /// Create service response for error
#[inline] #[inline]
pub fn error_response<B, E: Into<Error>>(self, err: E) -> ServiceResponse<B> { pub fn error_response<B, E: Into<Error>>(self, err: E) -> ServiceResponse<B> {
let res: Response = err.into().into(); let res: Response = err.into().into();
ServiceResponse::new(self.req, res.into_body()) ServiceResponse::new(self.0, res.into_body())
} }
/// This method returns reference to the request head /// This method returns reference to the request head
#[inline] #[inline]
pub fn head(&self) -> &RequestHead { pub fn head(&self) -> &RequestHead {
&self.req.head() &self.0.head()
} }
/// This method returns reference to the request head /// This method returns reference to the request head
#[inline] #[inline]
pub fn head_mut(&mut self) -> &mut RequestHead { pub fn head_mut(&mut self) -> &mut RequestHead {
self.req.head_mut() self.0.head_mut()
} }
/// Request's uri. /// Request's uri.
@ -164,34 +165,39 @@ impl ServiceRequest {
/// access the matched value for that segment. /// access the matched value for that segment.
#[inline] #[inline]
pub fn match_info(&self) -> &Path<Url> { pub fn match_info(&self) -> &Path<Url> {
self.req.match_info() self.0.match_info()
} }
#[inline] #[inline]
pub fn match_info_mut(&mut self) -> &mut Path<Url> { pub fn match_info_mut(&mut self) -> &mut Path<Url> {
self.req.match_info_mut() self.0.match_info_mut()
} }
/// Service configuration /// Service configuration
#[inline] #[inline]
pub fn app_config(&self) -> &AppConfig { pub fn app_config(&self) -> &AppConfig {
self.req.app_config() self.0.app_config()
} }
/// Get an application data stored with `App::data()` method during /// Get an application data stored with `App::data()` method during
/// application configuration. /// application configuration.
pub fn app_data<T: 'static>(&self) -> Option<Data<T>> { pub fn app_data<T: 'static>(&self) -> Option<Data<T>> {
if let Some(st) = self.req.0.app_data.get::<Data<T>>() { if let Some(st) = (self.0).0.app_data.get::<Data<T>>() {
Some(st.clone()) Some(st.clone())
} else { } else {
None None
} }
} }
/// Set request payload.
pub fn set_payload(&mut self, payload: Payload) {
Rc::get_mut(&mut (self.0).0).unwrap().payload = payload;
}
#[doc(hidden)] #[doc(hidden)]
/// Set new app data container /// Set new app data container
pub fn set_data_container(&mut self, extensions: Rc<Extensions>) { pub fn set_data_container(&mut self, extensions: Rc<Extensions>) {
Rc::get_mut(&mut self.req.0).unwrap().app_data = extensions; Rc::get_mut(&mut (self.0).0).unwrap().app_data = extensions;
} }
} }
@ -213,18 +219,18 @@ impl HttpMessage for ServiceRequest {
/// Request extensions /// Request extensions
#[inline] #[inline]
fn extensions(&self) -> Ref<Extensions> { fn extensions(&self) -> Ref<Extensions> {
self.req.extensions() self.0.extensions()
} }
/// Mutable reference to a the request's extensions /// Mutable reference to a the request's extensions
#[inline] #[inline]
fn extensions_mut(&self) -> RefMut<Extensions> { fn extensions_mut(&self) -> RefMut<Extensions> {
self.req.extensions_mut() self.0.extensions_mut()
} }
#[inline] #[inline]
fn take_payload(&mut self) -> Payload<Self::Stream> { fn take_payload(&mut self) -> Payload<Self::Stream> {
std::mem::replace(&mut self.payload, Payload::None) Rc::get_mut(&mut (self.0).0).unwrap().payload.take()
} }
} }

View File

@ -2,18 +2,19 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue}; use actix_http::http::header::{ContentType, Header, HeaderName, IntoHeaderValue};
use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version}; use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
use actix_http::test::TestRequest as HttpTestRequest; use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{cookie::Cookie, Extensions, Request}; use actix_http::{cookie::Cookie, Extensions, Request};
use actix_router::{Path, ResourceDef, Url}; use actix_router::{Path, ResourceDef, Url};
use actix_rt::Runtime; use actix_rt::{System, SystemRunner};
use actix_server_config::ServerConfig; use actix_server_config::ServerConfig;
use actix_service::{IntoNewService, IntoService, NewService, Service}; use actix_service::{IntoNewService, IntoService, NewService, Service};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::future::{lazy, ok, Future, IntoFuture}; use futures::future::{lazy, ok, Future, IntoFuture};
use futures::Stream; use futures::Stream;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json; use serde_json;
pub use actix_http::test::TestBuffer; pub use actix_http::test::TestBuffer;
@ -28,14 +29,14 @@ use crate::{Error, HttpRequest, HttpResponse};
thread_local! { thread_local! {
static RT: RefCell<Inner> = { static RT: RefCell<Inner> = {
RefCell::new(Inner(Some(Runtime::new().unwrap()))) RefCell::new(Inner(Some(System::builder().build())))
}; };
} }
struct Inner(Option<Runtime>); struct Inner(Option<SystemRunner>);
impl Inner { impl Inner {
fn get_mut(&mut self) -> &mut Runtime { fn get_mut(&mut self) -> &mut SystemRunner {
self.0.as_mut().unwrap() self.0.as_mut().unwrap()
} }
} }
@ -248,7 +249,7 @@ where
/// .header(header::CONTENT_TYPE, "application/json") /// .header(header::CONTENT_TYPE, "application/json")
/// .to_request(); /// .to_request();
/// ///
/// let resp = call_service(&mut srv, req); /// let resp = test::call_service(&mut app, req);
/// let result = test::read_body(resp); /// let result = test::read_body(resp);
/// assert_eq!(result, Bytes::from_static(b"welcome!")); /// assert_eq!(result, Bytes::from_static(b"welcome!"));
/// } /// }
@ -477,6 +478,16 @@ impl TestRequest {
self self
} }
/// Serialize `data` to JSON and set it as the request payload. The `Content-Type` header is
/// set to `application/json`.
pub fn set_json<T: Serialize>(mut self, data: &T) -> Self {
let bytes =
serde_json::to_string(data).expect("Failed to serialize test data to json");
self.req.set_payload(bytes);
self.req.set(ContentType::json());
self
}
/// Set application data. This is equivalent of `App::data()` method /// Set application data. This is equivalent of `App::data()` method
/// for testing purpose. /// for testing purpose.
pub fn data<T: 'static>(mut self, data: T) -> Self { pub fn data<T: 'static>(mut self, data: T) -> Self {
@ -501,16 +512,15 @@ impl TestRequest {
let (head, payload) = self.req.finish().into_parts(); let (head, payload) = self.req.finish().into_parts();
self.path.get_mut().update(&head.uri); self.path.get_mut().update(&head.uri);
let req = HttpRequest::new( ServiceRequest::new(HttpRequest::new(
self.path, self.path,
head, head,
payload,
Rc::new(self.rmap), Rc::new(self.rmap),
AppConfig::new(self.config), AppConfig::new(self.config),
Rc::new(self.app_data), Rc::new(self.app_data),
HttpRequestPool::create(), HttpRequestPool::create(),
); ))
ServiceRequest::from_parts(req, payload)
} }
/// Complete request creation and generate `ServiceResponse` instance /// Complete request creation and generate `ServiceResponse` instance
@ -520,12 +530,13 @@ impl TestRequest {
/// Complete request creation and generate `HttpRequest` instance /// Complete request creation and generate `HttpRequest` instance
pub fn to_http_request(mut self) -> HttpRequest { pub fn to_http_request(mut self) -> HttpRequest {
let (head, _) = self.req.finish().into_parts(); let (head, payload) = self.req.finish().into_parts();
self.path.get_mut().update(&head.uri); self.path.get_mut().update(&head.uri);
HttpRequest::new( HttpRequest::new(
self.path, self.path,
head, head,
payload,
Rc::new(self.rmap), Rc::new(self.rmap),
AppConfig::new(self.config), AppConfig::new(self.config),
Rc::new(self.app_data), Rc::new(self.app_data),
@ -541,6 +552,7 @@ impl TestRequest {
let req = HttpRequest::new( let req = HttpRequest::new(
self.path, self.path,
head, head,
Payload::None,
Rc::new(self.rmap), Rc::new(self.rmap),
AppConfig::new(self.config), AppConfig::new(self.config),
Rc::new(self.app_data), Rc::new(self.app_data),
@ -553,6 +565,7 @@ impl TestRequest {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use actix_http::httpmessage::HttpMessage;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::time::SystemTime; use std::time::SystemTime;
@ -657,6 +670,31 @@ mod tests {
assert_eq!(&result.id, "12345"); assert_eq!(&result.id, "12345");
} }
#[test]
fn test_request_response_json() {
let mut app = init_service(App::new().service(web::resource("/people").route(
web::post().to(|person: web::Json<Person>| {
HttpResponse::Ok().json(person.into_inner())
}),
)));
let payload = Person {
id: "12345".to_string(),
name: "User name".to_string(),
};
let req = TestRequest::post()
.uri("/people")
.set_json(&payload)
.to_request();
assert_eq!(req.content_type(), "application/json");
let result: Person = read_response_json(&mut app, req);
assert_eq!(&result.id, "12345");
assert_eq!(&result.name, "User name");
}
#[test] #[test]
fn test_async_with_block() { fn test_async_with_block() {
fn async_with_block() -> impl Future<Item = HttpResponse, Error = Error> { fn async_with_block() -> impl Future<Item = HttpResponse, Error = Error> {
@ -676,4 +714,42 @@ mod tests {
let res = block_fn(|| app.call(req)).unwrap(); let res = block_fn(|| app.call(req)).unwrap();
assert!(res.status().is_success()); assert!(res.status().is_success());
} }
#[test]
fn test_actor() {
use actix::Actor;
struct MyActor;
struct Num(usize);
impl actix::Message for Num {
type Result = usize;
}
impl actix::Actor for MyActor {
type Context = actix::Context<Self>;
}
impl actix::Handler<Num> for MyActor {
type Result = usize;
fn handle(&mut self, msg: Num, _: &mut Self::Context) -> Self::Result {
msg.0
}
}
let addr = run_on(|| MyActor.start());
let mut app = init_service(App::new().service(
web::resource("/index.html").to_async(move || {
addr.send(Num(1)).from_err().and_then(|res| {
if res == 1 {
HttpResponse::Ok()
} else {
HttpResponse::BadRequest()
}
})
}),
));
let req = TestRequest::post().uri("/index.html").to_request();
let res = block_fn(|| app.call(req)).unwrap();
assert!(res.status().is_success());
}
} }

View File

@ -175,15 +175,15 @@ where
#[inline] #[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let req2 = req.clone(); let req2 = req.clone();
let (limit, err) = req let (limit, err, ctype) = req
.app_data::<Self::Config>() .app_data::<Self::Config>()
.map(|c| (c.limit, c.ehandler.clone())) .map(|c| (c.limit, c.ehandler.clone(), c.content_type.clone()))
.unwrap_or((32768, None)); .unwrap_or((32768, None, None));
let path = req.path().to_string(); let path = req.path().to_string();
Box::new( Box::new(
JsonBody::new(req, payload) JsonBody::new(req, payload, ctype)
.limit(limit) .limit(limit)
.map_err(move |e| { .map_err(move |e| {
log::debug!( log::debug!(
@ -224,6 +224,9 @@ where
/// // change json extractor configuration /// // change json extractor configuration
/// web::Json::<Info>::configure(|cfg| { /// web::Json::<Info>::configure(|cfg| {
/// cfg.limit(4096) /// 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_handler(|err, req| { // <- create custom error response
/// error::InternalError::from_response( /// error::InternalError::from_response(
/// err, HttpResponse::Conflict().finish()).into() /// err, HttpResponse::Conflict().finish()).into()
@ -237,6 +240,7 @@ where
pub struct JsonConfig { pub struct JsonConfig {
limit: usize, limit: usize,
ehandler: Option<Arc<dyn Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync>>, ehandler: Option<Arc<dyn Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync>>,
content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
} }
impl JsonConfig { impl JsonConfig {
@ -254,6 +258,15 @@ impl JsonConfig {
self.ehandler = Some(Arc::new(f)); self.ehandler = Some(Arc::new(f));
self self
} }
/// Set predicate for allowed content types
pub fn content_type<F>(mut self, predicate: F) -> Self
where
F: Fn(mime::Mime) -> bool + Send + Sync + 'static,
{
self.content_type = Some(Arc::new(predicate));
self
}
} }
impl Default for JsonConfig { impl Default for JsonConfig {
@ -261,6 +274,7 @@ impl Default for JsonConfig {
JsonConfig { JsonConfig {
limit: 32768, limit: 32768,
ehandler: None, ehandler: None,
content_type: None,
} }
} }
} }
@ -271,6 +285,7 @@ impl Default for JsonConfig {
/// Returns error: /// Returns error:
/// ///
/// * content type is not `application/json` /// * content type is not `application/json`
/// (unless specified in [`JsonConfig`](struct.JsonConfig.html))
/// * content length is greater than 256k /// * content length is greater than 256k
pub struct JsonBody<U> { pub struct JsonBody<U> {
limit: usize, limit: usize,
@ -285,13 +300,20 @@ where
U: DeserializeOwned + 'static, U: DeserializeOwned + 'static,
{ {
/// Create `JsonBody` for request. /// Create `JsonBody` for request.
pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self { pub fn new(
req: &HttpRequest,
payload: &mut Payload,
ctype: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
) -> Self {
// check content-type // check content-type
let json = if let Ok(Some(mime)) = req.mime_type() { let json = if let Ok(Some(mime)) = req.mime_type() {
mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON) mime.subtype() == mime::JSON
|| mime.suffix() == Some(mime::JSON)
|| ctype.as_ref().map_or(false, |predicate| predicate(mime))
} else { } else {
false false
}; };
if !json { if !json {
return JsonBody { return JsonBody {
limit: 262_144, limit: 262_144,
@ -512,7 +534,7 @@ mod tests {
#[test] #[test]
fn test_json_body() { fn test_json_body() {
let (req, mut pl) = TestRequest::default().to_http_parts(); let (req, mut pl) = TestRequest::default().to_http_parts();
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl)); let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None));
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
let (req, mut pl) = TestRequest::default() let (req, mut pl) = TestRequest::default()
@ -521,7 +543,7 @@ mod tests {
header::HeaderValue::from_static("application/text"), header::HeaderValue::from_static("application/text"),
) )
.to_http_parts(); .to_http_parts();
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl)); let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None));
assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType));
let (req, mut pl) = TestRequest::default() let (req, mut pl) = TestRequest::default()
@ -535,7 +557,7 @@ mod tests {
) )
.to_http_parts(); .to_http_parts();
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl).limit(100)); let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None).limit(100));
assert!(json_eq(json.err().unwrap(), JsonPayloadError::Overflow)); assert!(json_eq(json.err().unwrap(), JsonPayloadError::Overflow));
let (req, mut pl) = TestRequest::default() let (req, mut pl) = TestRequest::default()
@ -550,7 +572,7 @@ mod tests {
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.to_http_parts(); .to_http_parts();
let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl)); let json = block_on(JsonBody::<MyObject>::new(&req, &mut pl, None));
assert_eq!( assert_eq!(
json.ok().unwrap(), json.ok().unwrap(),
MyObject { MyObject {
@ -558,4 +580,62 @@ mod tests {
} }
); );
} }
#[test]
fn test_with_json_and_bad_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().limit(4096))
.to_http_parts();
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
assert!(s.is_err())
}
#[test]
fn test_with_json_and_good_custom_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
assert!(s.is_ok())
}
#[test]
fn test_with_json_and_bad_custom_content_type() {
let (req, mut pl) = TestRequest::with_header(
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/html"),
)
.header(
header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"),
)
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.data(JsonConfig::default().content_type(|mime: mime::Mime| {
mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
}))
.to_http_parts();
let s = block_on(Json::<MyObject>::from_request(&req, &mut pl));
assert!(s.is_err())
}
} }

View File

@ -9,6 +9,6 @@ pub(crate) mod readlines;
pub use self::form::{Form, FormConfig}; pub use self::form::{Form, FormConfig};
pub use self::json::{Json, JsonConfig}; pub use self::json::{Json, JsonConfig};
pub use self::path::Path; pub use self::path::{Path, PathConfig};
pub use self::payload::{Payload, PayloadConfig}; pub use self::payload::{Payload, PayloadConfig};
pub use self::query::{Query, QueryConfig}; pub use self::query::{Query, QueryConfig};

View File

@ -1,5 +1,6 @@
//! Path extractor //! Path extractor
use std::sync::Arc;
use std::{fmt, ops}; use std::{fmt, ops};
use actix_http::error::{Error, ErrorNotFound}; use actix_http::error::{Error, ErrorNotFound};
@ -7,6 +8,7 @@ use actix_router::PathDeserializer;
use serde::de; use serde::de;
use crate::dev::Payload; use crate::dev::Payload;
use crate::error::PathError;
use crate::request::HttpRequest; use crate::request::HttpRequest;
use crate::FromRequest; use crate::FromRequest;
@ -156,15 +158,89 @@ impl<T> FromRequest for Path<T>
where where
T: de::DeserializeOwned, T: de::DeserializeOwned,
{ {
type Config = ();
type Error = Error; type Error = Error;
type Future = Result<Self, Error>; type Future = Result<Self, Error>;
type Config = PathConfig;
#[inline] #[inline]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
let error_handler = req
.app_data::<Self::Config>()
.map(|c| c.ehandler.clone())
.unwrap_or(None);
de::Deserialize::deserialize(PathDeserializer::new(req.match_info())) de::Deserialize::deserialize(PathDeserializer::new(req.match_info()))
.map(|inner| Path { inner }) .map(|inner| Path { inner })
.map_err(ErrorNotFound) .map_err(move |e| {
log::debug!(
"Failed during Path extractor deserialization. \
Request path: {:?}",
req.path()
);
if let Some(error_handler) = error_handler {
let e = PathError::Deserialize(e);
(error_handler)(e, req)
} else {
ErrorNotFound(e)
}
})
}
}
/// Path extractor configuration
///
/// ```rust
/// # #[macro_use]
/// # extern crate serde_derive;
/// use actix_web::web::PathConfig;
/// use actix_web::{error, web, App, FromRequest, HttpResponse};
///
/// #[derive(Deserialize, Debug)]
/// enum Folder {
/// #[serde(rename = "inbox")]
/// Inbox,
/// #[serde(rename = "outbox")]
/// Outbox,
/// }
///
/// // deserialize `Info` from request's path
/// fn index(folder: web::Path<Folder>) -> String {
/// format!("Selected folder: {:?}!", folder)
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/messages/{folder}")
/// .data(PathConfig::default().error_handler(|err, req| {
/// error::InternalError::from_response(
/// err,
/// HttpResponse::Conflict().finish(),
/// )
/// .into()
/// }))
/// .route(web::post().to(index)),
/// );
/// }
/// ```
#[derive(Clone)]
pub struct PathConfig {
ehandler: Option<Arc<Fn(PathError, &HttpRequest) -> Error + Send + Sync>>,
}
impl PathConfig {
/// Set custom error handler
pub fn error_handler<F>(mut self, f: F) -> Self
where
F: Fn(PathError, &HttpRequest) -> Error + Send + Sync + 'static,
{
self.ehandler = Some(Arc::new(f));
self
}
}
impl Default for PathConfig {
fn default() -> Self {
PathConfig { ehandler: None }
} }
} }
@ -176,6 +252,7 @@ mod tests {
use super::*; use super::*;
use crate::test::{block_on, TestRequest}; use crate::test::{block_on, TestRequest};
use crate::{error, http, HttpResponse};
#[derive(Deserialize, Debug, Display)] #[derive(Deserialize, Debug, Display)]
#[display(fmt = "MyStruct({}, {})", key, value)] #[display(fmt = "MyStruct({}, {})", key, value)]
@ -271,4 +348,21 @@ mod tests {
assert_eq!(res[1], "32".to_owned()); assert_eq!(res[1], "32".to_owned());
} }
#[test]
fn test_custom_err_handler() {
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
.data(PathConfig::default().error_handler(|err, _| {
error::InternalError::from_response(
err,
HttpResponse::Conflict().finish(),
)
.into()
}))
.to_http_parts();
let s = block_on(Path::<(usize,)>::from_request(&req, &mut pl)).unwrap_err();
let res: HttpResponse = s.into();
assert_eq!(res.status(), http::StatusCode::CONFLICT);
}
} }

View File

@ -1,5 +1,13 @@
# Changes # Changes
## [0.2.2] - 2019-06-16
* Add .put() and .sput() methods
## [0.2.1] - 2019-06-05
* Add license files
## [0.2.0] - 2019-05-12 ## [0.2.0] - 2019-05-12
* Update awc and actix-http deps * Update awc and actix-http deps

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-http-test" name = "actix-http-test"
version = "0.2.0" version = "0.2.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http test server" description = "Actix http test server"
readme = "README.md" readme = "README.md"
@ -32,10 +32,10 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
[dependencies] [dependencies]
actix-codec = "0.1.2" actix-codec = "0.1.2"
actix-rt = "0.2.2" actix-rt = "0.2.2"
actix-service = "0.4.0" actix-service = "0.4.1"
actix-server = "0.5.0" actix-server = "0.5.1"
actix-utils = "0.4.0" actix-utils = "0.4.1"
awc = "0.2.0" awc = "0.2.1"
base64 = "0.10" base64 = "0.10"
bytes = "0.4" bytes = "0.4"
@ -55,5 +55,5 @@ tokio-timer = "0.2"
openssl = { version="0.10", optional = true } openssl = { version="0.10", optional = true }
[dev-dependencies] [dev-dependencies]
actix-web = "1.0.0-beta.4" actix-web = "1.0.0"
actix-http = "0.2.0" actix-http = "0.2.4"

1
test-server/LICENSE-APACHE Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-APACHE

1
test-server/LICENSE-MIT Symbolic link
View File

@ -0,0 +1 @@
../LICENSE-MIT

View File

@ -255,6 +255,16 @@ impl TestServerRuntime {
self.client.head(self.surl(path.as_ref()).as_str()) self.client.head(self.surl(path.as_ref()).as_str())
} }
/// Create `PUT` request
pub fn put<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.put(self.url(path.as_ref()).as_str())
}
/// Create https `PUT` request
pub fn sput<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.put(self.surl(path.as_ref()).as_str())
}
/// Connect to test http server /// Connect to test http server
pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest { pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest {
self.client.request(method, path.as_ref()) self.client.request(method, path.as_ref())