mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-04 01:51:30 +02:00
Compare commits
38 Commits
codegen-v0
...
web-v1.0.1
Author | SHA1 | Date | |
---|---|---|---|
acda1c075a | |||
686e5f1595 | |||
d2b6502c7a | |||
7c0f570845 | |||
eaa371db8b | |||
d293ae2a69 | |||
d7ec241fd0 | |||
cd323f2ff1 | |||
bf48798bce | |||
c8118e8411 | |||
e7ba67e1a8 | |||
13e618b128 | |||
36e6f0cb4b | |||
7450ae37a7 | |||
2ffda29f9b | |||
ff724e239d | |||
ee769832cf | |||
c4b7980b4f | |||
bfbac4f875 | |||
53e2f8090f | |||
e399e01a22 | |||
d9a62c4bbf | |||
a548b69679 | |||
ae64475d98 | |||
a342b1289d | |||
38f04b75a7 | |||
a771540b16 | |||
cf217d35a8 | |||
0e138e111f | |||
1fce4876f3 | |||
4a179d1ae1 | |||
a780ea10e9 | |||
6d2e190c8e | |||
b1cfbdcf7a | |||
24180f9014 | |||
15cdc680f6 | |||
666756bfbe | |||
a1b40f4314 |
31
CHANGES.md
31
CHANGES.md
@ -1,14 +1,43 @@
|
||||
# Changes
|
||||
|
||||
## [1.0.0] - 2019-05-xx
|
||||
## [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
|
||||
|
35
Cargo.toml
35
Cargo.toml
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "1.0.0"
|
||||
version = "1.0.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
@ -31,9 +31,11 @@ members = [
|
||||
".",
|
||||
"awc",
|
||||
"actix-http",
|
||||
"actix-cors",
|
||||
"actix-files",
|
||||
"actix-framed",
|
||||
"actix-session",
|
||||
"actix-identity",
|
||||
"actix-multipart",
|
||||
"actix-web-actors",
|
||||
"actix-web-codegen",
|
||||
@ -41,7 +43,7 @@ members = [
|
||||
]
|
||||
|
||||
[features]
|
||||
default = ["brotli", "flate2-zlib", "secure-cookies", "client", "fail"]
|
||||
default = ["brotli", "flate2-zlib", "client", "fail", "depracated"]
|
||||
|
||||
# http client
|
||||
client = ["awc"]
|
||||
@ -66,24 +68,31 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
# rustls
|
||||
rust-tls = ["rustls", "actix-server/rust-tls"]
|
||||
|
||||
# deprecated middlewares
|
||||
depracated = ["actix-cors", "actix-identity"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.0"
|
||||
actix-service = "0.4.1"
|
||||
actix-utils = "0.4.1"
|
||||
actix-router = "0.1.5"
|
||||
actix-rt = "0.2.2"
|
||||
actix-web-codegen = "0.1.0"
|
||||
actix-http = "0.2.2"
|
||||
actix-web-codegen = "0.1.2"
|
||||
actix-http = "0.2.4"
|
||||
actix-server = "0.5.1"
|
||||
actix-server-config = "0.1.1"
|
||||
actix-threadpool = "0.1.0"
|
||||
awc = { version = "0.2.0", optional = true }
|
||||
actix-threadpool = "0.1.1"
|
||||
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"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
encoding = "0.2"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
hashbrown = "0.5.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
net2 = "0.2.33"
|
||||
@ -100,9 +109,9 @@ openssl = { version="0.10", optional = true }
|
||||
rustls = { version = "0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-http = { version = "0.2.2", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-files = { version = "0.1.0" }
|
||||
actix = { version = "0.8.3" }
|
||||
actix-http = { version = "0.2.4", features=["ssl", "brotli", "flate2-zlib"] }
|
||||
actix-http-test = { version = "0.2.2", features=["ssl"] }
|
||||
rand = "0.6"
|
||||
env_logger = "0.6"
|
||||
serde_derive = "1.0"
|
||||
@ -116,7 +125,7 @@ opt-level = 3
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
actix-web = { path = "." }
|
||||
# actix-web = { path = "." }
|
||||
actix-http = { path = "actix-http" }
|
||||
actix-http-test = { path = "test-server" }
|
||||
actix-web-codegen = { path = "actix-web-codegen" }
|
||||
|
33
MIGRATION.md
33
MIGRATION.md
@ -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
|
||||
registration via `.service()` method.
|
||||
|
@ -11,7 +11,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
* Multipart streams
|
||||
* Static assets
|
||||
* 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)
|
||||
* 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/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* 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
|
||||
|
||||
|
5
actix-cors/CHANGES.md
Normal file
5
actix-cors/CHANGES.md
Normal 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
23
actix-cors/Cargo.toml
Normal 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
1
actix-cors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-cors/LICENSE-MIT
Symbolic link
1
actix-cors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
9
actix-cors/README.md
Normal file
9
actix-cors/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](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
|
@ -7,7 +7,7 @@
|
||||
//! # Example
|
||||
//!
|
||||
//! ```rust
|
||||
//! use actix_web::middleware::cors::Cors;
|
||||
//! use actix_cors::Cors;
|
||||
//! use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
|
||||
//!
|
||||
//! fn index(req: HttpRequest) -> &'static str {
|
||||
@ -42,17 +42,15 @@ use std::iter::FromIterator;
|
||||
use std::rc::Rc;
|
||||
|
||||
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 futures::future::{ok, Either, Future, FutureResult};
|
||||
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
|
||||
#[derive(Debug, Display)]
|
||||
pub enum CorsError {
|
||||
@ -152,11 +150,11 @@ impl<T> AllOrSome<T> {
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_cors::Cors;
|
||||
/// use actix_web::http::header;
|
||||
/// use actix_web::middleware::cors;
|
||||
///
|
||||
/// # fn main() {
|
||||
/// let cors = cors::Cors::new()
|
||||
/// let cors = Cors::new()
|
||||
/// .allowed_origin("https://www.rust-lang.org/")
|
||||
/// .allowed_methods(vec!["GET", "POST"])
|
||||
/// .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT])
|
||||
@ -806,9 +804,9 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use actix_service::{IntoService, Transform};
|
||||
use actix_web::test::{self, block_on, TestRequest};
|
||||
|
||||
use super::*;
|
||||
use crate::test::{self, block_on, TestRequest};
|
||||
|
||||
impl Cors {
|
||||
fn finish<F, S, B>(self, srv: F) -> CorsMiddleware<S>
|
@ -1,5 +1,15 @@
|
||||
# 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
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-files"
|
||||
version = "0.1.0"
|
||||
version = "0.1.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Static files support for actix web."
|
||||
readme = "README.md"
|
||||
@ -18,12 +18,13 @@ name = "actix_files"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-rc"
|
||||
actix-service = "0.4.0"
|
||||
actix-web = { version = "1.0.0", default-features = false }
|
||||
actix-http = "0.2.4"
|
||||
actix-service = "0.4.1"
|
||||
bitflags = "1"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
log = "0.4"
|
||||
mime = "0.3"
|
||||
mime_guess = "2.0.0-alpha"
|
||||
@ -31,4 +32,4 @@ percent-encoding = "1.0"
|
||||
v_htmlescape = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-rc", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0", features=["ssl"] }
|
||||
|
1
actix-files/LICENSE-APACHE
Symbolic link
1
actix-files/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-files/LICENSE-MIT
Symbolic link
1
actix-files/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -926,6 +926,29 @@ mod tests {
|
||||
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]
|
||||
fn test_static_files_with_spaces() {
|
||||
let mut srv = test::init_service(
|
||||
|
@ -11,6 +11,7 @@ use bitflags::bitflags;
|
||||
use mime;
|
||||
use mime_guess::guess_mime_type;
|
||||
|
||||
use actix_http::body::SizedStream;
|
||||
use actix_web::http::header::{
|
||||
self, ContentDisposition, DispositionParam, DispositionType,
|
||||
};
|
||||
@ -421,20 +422,16 @@ impl Responder for NamedFile {
|
||||
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish());
|
||||
}
|
||||
|
||||
if *req.method() == Method::HEAD {
|
||||
Ok(resp.finish())
|
||||
} else {
|
||||
let reader = ChunkedReadFile {
|
||||
offset,
|
||||
size: length,
|
||||
file: Some(self.file),
|
||||
fut: None,
|
||||
counter: 0,
|
||||
};
|
||||
if offset != 0 || length != self.md.len() {
|
||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||
};
|
||||
Ok(resp.streaming(reader))
|
||||
}
|
||||
let reader = ChunkedReadFile {
|
||||
offset,
|
||||
size: length,
|
||||
file: Some(self.file),
|
||||
fut: None,
|
||||
counter: 0,
|
||||
};
|
||||
if offset != 0 || length != self.md.len() {
|
||||
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
|
||||
};
|
||||
Ok(resp.body(SizedStream::new(length, reader)))
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,25 @@
|
||||
# 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
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "0.2.2"
|
||||
version = "0.2.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http primitives"
|
||||
readme = "README.md"
|
||||
@ -56,11 +56,11 @@ bitflags = "1.0"
|
||||
bytes = "0.4"
|
||||
byteorder = "1.2"
|
||||
copyless = "0.1.2"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
either = "1.5.2"
|
||||
encoding = "0.2"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
hashbrown = "0.5.0"
|
||||
h2 = "0.1.16"
|
||||
http = "0.1.17"
|
||||
httparse = "1.3"
|
||||
|
@ -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 {
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.len())
|
||||
@ -366,7 +385,7 @@ where
|
||||
/// 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.
|
||||
pub struct SizedStream<S> {
|
||||
size: usize,
|
||||
size: u64,
|
||||
stream: S,
|
||||
}
|
||||
|
||||
@ -374,7 +393,7 @@ impl<S> SizedStream<S>
|
||||
where
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@ -384,7 +403,7 @@ where
|
||||
S: Stream<Item = Bytes, Error = Error>,
|
||||
{
|
||||
fn size(&self) -> BodySize {
|
||||
BodySize::Sized(self.size)
|
||||
BodySize::Sized64(self.size)
|
||||
}
|
||||
|
||||
fn poll_next(&mut self) -> Poll<Option<Bytes>, Error> {
|
||||
|
@ -33,6 +33,7 @@ impl<B: MessageBody> Encoder<B> {
|
||||
) -> ResponseBody<Encoder<B>> {
|
||||
let can_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
||||
|| head.status == StatusCode::SWITCHING_PROTOCOLS
|
||||
|| head.status == StatusCode::NO_CONTENT
|
||||
|| encoding == ContentEncoding::Identity
|
||||
|| encoding == ContentEncoding::Auto);
|
||||
|
||||
|
@ -693,11 +693,12 @@ where
|
||||
}
|
||||
} else {
|
||||
// read socket into a buf
|
||||
let should_disconnect = if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||
read_available(&mut inner.io, &mut inner.read_buf)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let should_disconnect =
|
||||
if !inner.flags.contains(Flags::READ_DISCONNECT) {
|
||||
read_available(&mut inner.io, &mut inner.read_buf)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
inner.poll_request()?;
|
||||
if let Some(true) = should_disconnect {
|
||||
|
@ -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
|
||||
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
|
||||
fn from(res: Result<I, E>) -> Self {
|
||||
|
@ -12,7 +12,6 @@ use futures::stream::{once, Stream};
|
||||
use regex::Regex;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use actix_http::body::Body;
|
||||
use actix_http::error::PayloadError;
|
||||
use actix_http::{
|
||||
body, error, http, http::header, Error, HttpService, KeepAlive, Request, Response,
|
||||
@ -218,30 +217,28 @@ fn test_expect_continue_h1() {
|
||||
|
||||
#[test]
|
||||
fn test_chunked_payload() {
|
||||
let chunk_sizes = vec![ 32768, 32, 32768 ];
|
||||
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))
|
||||
})
|
||||
})
|
||||
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");
|
||||
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();
|
||||
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[..]);
|
||||
@ -826,8 +823,7 @@ fn test_h1_body_length() {
|
||||
HttpService::build().h1(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(Body::from_message(body::SizedStream::new(STR.len(), body))),
|
||||
Response::Ok().body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
});
|
||||
@ -852,9 +848,10 @@ fn test_h2_body_length() {
|
||||
HttpService::build()
|
||||
.h2(|_| {
|
||||
let body = once(Ok(Bytes::from_static(STR.as_ref())));
|
||||
ok::<_, ()>(Response::Ok().body(Body::from_message(
|
||||
body::SizedStream::new(STR.len(), body),
|
||||
)))
|
||||
ok::<_, ()>(
|
||||
Response::Ok()
|
||||
.body(body::SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ()),
|
||||
)
|
||||
|
5
actix-identity/CHANGES.md
Normal file
5
actix-identity/CHANGES.md
Normal 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
30
actix-identity/Cargo.toml
Normal 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"
|
1
actix-identity/LICENSE-APACHE
Symbolic link
1
actix-identity/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-identity/LICENSE-MIT
Symbolic link
1
actix-identity/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
9
actix-identity/README.md
Normal file
9
actix-identity/README.md
Normal file
@ -0,0 +1,9 @@
|
||||
# Identity service for actix web framework [](https://travis-ci.org/actix/actix-web) [](https://codecov.io/gh/actix/actix-web) [](https://crates.io/crates/actix-identity) [](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
|
@ -10,12 +10,11 @@
|
||||
//! uses cookies as identity storage.
|
||||
//!
|
||||
//! To access current request identity
|
||||
//! [**Identity**](trait.Identity.html) extractor should be used.
|
||||
//! [**Identity**](struct.Identity.html) extractor should be used.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use actix_web::middleware::identity::Identity;
|
||||
//! use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
||||
//! use actix_web::*;
|
||||
//! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
|
||||
//!
|
||||
//! fn index(id: Identity) -> String {
|
||||
//! // access request identity
|
||||
@ -39,7 +38,7 @@
|
||||
//! fn main() {
|
||||
//! let app = App::new().wrap(IdentityService::new(
|
||||
//! // <- create identity middleware
|
||||
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie session backend
|
||||
//! CookieIdentityPolicy::new(&[0; 32]) // <- create cookie identity policy
|
||||
//! .name("auth-cookie")
|
||||
//! .secure(false)))
|
||||
//! .service(web::resource("/index.html").to(index))
|
||||
@ -57,17 +56,17 @@ use futures::{Future, IntoFuture, Poll};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::Duration;
|
||||
|
||||
use crate::cookie::{Cookie, CookieJar, Key, SameSite};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::http::header::{self, HeaderValue};
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::{dev::Payload, FromRequest, HttpMessage, HttpRequest};
|
||||
use actix_web::cookie::{Cookie, CookieJar, Key, SameSite};
|
||||
use actix_web::dev::{Extensions, Payload, ServiceRequest, ServiceResponse};
|
||||
use actix_web::error::{Error, Result};
|
||||
use actix_web::http::header::{self, HeaderValue};
|
||||
use actix_web::{FromRequest, HttpMessage, HttpRequest};
|
||||
|
||||
/// The extractor type to obtain your identity from a request.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::*;
|
||||
/// use actix_web::middleware::identity::Identity;
|
||||
/// use actix_identity::Identity;
|
||||
///
|
||||
/// fn index(id: Identity) -> Result<String> {
|
||||
/// // access request identity
|
||||
@ -96,11 +95,7 @@ impl Identity {
|
||||
/// Return the claimed identity of the user associated request or
|
||||
/// ``None`` if no identity can be found associated with the request.
|
||||
pub fn identity(&self) -> Option<String> {
|
||||
if let Some(id) = self.0.extensions().get::<IdentityItem>() {
|
||||
id.id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
Identity::get_identity(&self.0.extensions())
|
||||
}
|
||||
|
||||
/// Remember identity.
|
||||
@ -119,6 +114,14 @@ impl Identity {
|
||||
id.changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn get_identity(extensions: &Extensions) -> Option<String> {
|
||||
if let Some(id) = extensions.get::<IdentityItem>() {
|
||||
id.id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct IdentityItem {
|
||||
@ -126,11 +129,28 @@ struct IdentityItem {
|
||||
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.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use actix_web::*;
|
||||
/// use actix_web::middleware::identity::Identity;
|
||||
/// use actix_identity::Identity;
|
||||
///
|
||||
/// fn index(id: Identity) -> String {
|
||||
/// // access request identity
|
||||
@ -177,7 +197,7 @@ pub trait IdentityPolicy: Sized + 'static {
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::App;
|
||||
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
||||
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().wrap(IdentityService::new(
|
||||
@ -442,9 +462,8 @@ impl CookieIdentityInner {
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// use actix_web::middleware::identity::{CookieIdentityPolicy, IdentityService};
|
||||
/// use actix_web::App;
|
||||
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().wrap(IdentityService::new(
|
||||
@ -590,13 +609,13 @@ impl IdentityPolicy for CookieIdentityPolicy {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::http::StatusCode;
|
||||
use crate::test::{self, TestRequest};
|
||||
use crate::{web, App, HttpResponse};
|
||||
|
||||
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_NAME: &'static str = "actix_auth";
|
||||
const COOKIE_LOGIN: &'static str = "test";
|
||||
@ -717,8 +736,8 @@ mod tests {
|
||||
f: F,
|
||||
) -> impl actix_service::Service<
|
||||
Request = actix_http::Request,
|
||||
Response = ServiceResponse<actix_http::body::Body>,
|
||||
Error = actix_http::Error,
|
||||
Response = ServiceResponse<actix_web::body::Body>,
|
||||
Error = Error,
|
||||
> {
|
||||
test::init_service(
|
||||
App::new()
|
@ -1,5 +1,13 @@
|
||||
# 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
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-multipart"
|
||||
version = "0.1.1"
|
||||
version = "0.1.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Multipart support for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -18,10 +18,10 @@ name = "actix_multipart"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-rc"
|
||||
actix-service = "0.4.0"
|
||||
actix-web = { version = "1.0.0", default-features = false }
|
||||
actix-service = "0.4.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
httparse = "1.3"
|
||||
futures = "0.1.25"
|
||||
log = "0.4"
|
||||
@ -31,4 +31,4 @@ twoway = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-http = "0.2.0"
|
||||
actix-http = "0.2.4"
|
1
actix-multipart/LICENSE-APACHE
Symbolic link
1
actix-multipart/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-multipart/LICENSE-MIT
Symbolic link
1
actix-multipart/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -537,8 +537,6 @@ impl InnerField {
|
||||
if &payload.buf[b_len..b_size] == boundary.as_bytes() {
|
||||
// found boundary
|
||||
return Ok(Async::Ready(None));
|
||||
} else {
|
||||
pos = b_size;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -576,7 +574,7 @@ impl InnerField {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Ok(Async::Ready(Some(payload.buf.take().freeze())));
|
||||
Ok(Async::Ready(Some(payload.buf.take().freeze())))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2019-06-03
|
||||
|
||||
* Fix optional cookie session support
|
||||
|
||||
## [0.1.0] - 2019-05-18
|
||||
|
||||
* Use actix-web 1.0.0-rc
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-session"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Session for actix web framework."
|
||||
readme = "README.md"
|
||||
@ -24,12 +24,12 @@ default = ["cookie-session"]
|
||||
cookie-session = ["actix-web/secure-cookies"]
|
||||
|
||||
[dependencies]
|
||||
actix-web = "1.0.0-rc"
|
||||
actix-service = "0.4.0"
|
||||
actix-web = "1.0.0"
|
||||
actix-service = "0.4.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
futures = "0.1.25"
|
||||
hashbrown = "0.3.0"
|
||||
hashbrown = "0.5.0"
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
time = "0.1.42"
|
||||
|
1
actix-session/LICENSE-APACHE
Symbolic link
1
actix-session/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-session/LICENSE-MIT
Symbolic link
1
actix-session/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -52,7 +52,9 @@ use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
|
||||
#[cfg(feature = "cookie-session")]
|
||||
mod cookie;
|
||||
#[cfg(feature = "cookie-session")]
|
||||
pub use crate::cookie::CookieSession;
|
||||
|
||||
/// The high-level interface you use to modify session data.
|
||||
|
@ -19,8 +19,8 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix = "0.8.3"
|
||||
actix-web = "1.0.0-rc"
|
||||
actix-http = "0.2.2"
|
||||
actix-web = "1.0.0"
|
||||
actix-http = "0.2.4"
|
||||
actix-codec = "0.1.2"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.25"
|
||||
|
1
actix-web-actors/LICENSE-APACHE
Symbolic link
1
actix-web-actors/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-web-actors/LICENSE-MIT
Symbolic link
1
actix-web-actors/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -1,5 +1,9 @@
|
||||
# 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
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-codegen"
|
||||
version = "0.1.1"
|
||||
version = "0.1.2"
|
||||
description = "Actix web proc macros"
|
||||
readme = "README.md"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
@ -16,7 +16,7 @@ quote = "0.6.12"
|
||||
syn = { version = "0.15.34", features = ["full", "parsing", "extra-traits"] }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = { version = "1.0.0-rc" }
|
||||
actix-http = { version = "0.2.2", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0" }
|
||||
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
futures = { version = "0.1" }
|
||||
|
@ -11,6 +11,11 @@
|
||||
//! - [post](attr.post.html)
|
||||
//! - [put](attr.put.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:
|
||||
//!
|
||||
@ -92,3 +97,63 @@ pub fn delete(args: TokenStream, input: TokenStream) -> TokenStream {
|
||||
let gen = route::Args::new(&args, input, route::GuardType::Delete);
|
||||
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()
|
||||
}
|
||||
|
@ -25,6 +25,11 @@ pub enum GuardType {
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Head,
|
||||
Connect,
|
||||
Options,
|
||||
Trace,
|
||||
Patch,
|
||||
}
|
||||
|
||||
impl fmt::Display for GuardType {
|
||||
@ -34,6 +39,11 @@ impl fmt::Display for GuardType {
|
||||
&GuardType::Post => write!(f, "Post"),
|
||||
&GuardType::Put => write!(f, "Put"),
|
||||
&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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
use actix_http::HttpService;
|
||||
use actix_http_test::TestServer;
|
||||
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};
|
||||
|
||||
#[get("/test")]
|
||||
@ -14,11 +14,36 @@ fn put_test() -> impl Responder {
|
||||
HttpResponse::Created()
|
||||
}
|
||||
|
||||
#[patch("/test")]
|
||||
fn patch_test() -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
#[post("/test")]
|
||||
fn post_test() -> impl Responder {
|
||||
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")]
|
||||
fn auto_async() -> impl Future<Item = HttpResponse, Error = actix_web::Error> {
|
||||
future::ok(HttpResponse::Ok().finish())
|
||||
@ -75,6 +100,11 @@ fn test_body() {
|
||||
App::new()
|
||||
.service(post_test)
|
||||
.service(put_test)
|
||||
.service(head_test)
|
||||
.service(connect_test)
|
||||
.service(options_test)
|
||||
.service(trace_test)
|
||||
.service(patch_test)
|
||||
.service(test),
|
||||
)
|
||||
});
|
||||
@ -82,6 +112,26 @@ fn test_body() {
|
||||
let response = srv.block_on(request.send()).unwrap();
|
||||
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 response = srv.block_on(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
@ -1,5 +1,11 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-06-05
|
||||
|
||||
### Added
|
||||
|
||||
* Add license files
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Added
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "awc"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http client."
|
||||
readme = "README.md"
|
||||
@ -40,11 +40,11 @@ flate2-rust = ["actix-http/flate2-rust"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-service = "0.4.0"
|
||||
actix-http = "0.2.0"
|
||||
actix-service = "0.4.1"
|
||||
actix-http = "0.2.4"
|
||||
base64 = "0.10.1"
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
derive_more = "0.15.0"
|
||||
futures = "0.1.25"
|
||||
log =" 0.4"
|
||||
mime = "0.3"
|
||||
@ -58,11 +58,11 @@ openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-web = { version = "1.0.0-beta.4", features=["ssl"] }
|
||||
actix-http = { version = "0.2.0", features=["ssl"] }
|
||||
actix-web = { version = "1.0.0", features=["ssl"] }
|
||||
actix-http = { version = "0.2.4", features=["ssl"] }
|
||||
actix-http-test = { version = "0.2.0", features=["ssl"] }
|
||||
actix-utils = "0.4.0"
|
||||
actix-server = { version = "0.5.0", features=["ssl"] }
|
||||
actix-utils = "0.4.1"
|
||||
actix-server = { version = "0.5.1", features=["ssl"] }
|
||||
brotli2 = { version="0.3.2" }
|
||||
flate2 = { version="1.0.2" }
|
||||
env_logger = "0.6"
|
||||
|
1
awc/LICENSE-APACHE
Symbolic link
1
awc/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
awc/LICENSE-MIT
Symbolic link
1
awc/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -38,6 +38,7 @@ pub mod test;
|
||||
pub mod ws;
|
||||
|
||||
pub use self::builder::ClientBuilder;
|
||||
pub use self::connect::BoxedSocket;
|
||||
pub use self::request::ClientRequest;
|
||||
pub use self::response::{ClientResponse, JsonBody, MessageBody};
|
||||
|
||||
|
10
src/app.rs
10
src/app.rs
@ -100,6 +100,13 @@ where
|
||||
self
|
||||
}
|
||||
|
||||
/// Set application data. Application data could be accessed
|
||||
/// by using `Data<T>` extractor where `T` is data type.
|
||||
pub fn register_data<U: 'static>(mut self, data: Data<U>) -> Self {
|
||||
self.data.push(Box::new(data));
|
||||
self
|
||||
}
|
||||
|
||||
/// Run external configuration as part of the application building
|
||||
/// process
|
||||
///
|
||||
@ -218,7 +225,6 @@ where
|
||||
/// It is also possible to use static files as default service.
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_files::Files;
|
||||
/// use actix_web::{web, App, HttpResponse};
|
||||
///
|
||||
/// fn main() {
|
||||
@ -226,7 +232,7 @@ where
|
||||
/// .service(
|
||||
/// web::resource("/index.html").to(|| HttpResponse::Ok()))
|
||||
/// .default_service(
|
||||
/// Files::new("", "./static")
|
||||
/// web::to(|| HttpResponse::NotFound())
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
|
@ -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.
|
||||
///
|
||||
/// This is same as `App::data()` method.
|
||||
|
23
src/data.rs
23
src/data.rs
@ -54,7 +54,7 @@ pub(crate) trait DataFactory {
|
||||
///
|
||||
/// let app = App::new()
|
||||
/// // Store `MyData` in application storage.
|
||||
/// .data(data.clone())
|
||||
/// .register_data(data.clone())
|
||||
/// .service(
|
||||
/// web::resource("/index.html").route(
|
||||
/// web::get().to(index)));
|
||||
@ -130,6 +130,7 @@ impl<T: 'static> DataFactory for Data<T> {
|
||||
mod tests {
|
||||
use actix_service::Service;
|
||||
|
||||
use super::*;
|
||||
use crate::http::StatusCode;
|
||||
use crate::test::{block_on, init_service, TestRequest};
|
||||
use crate::{web, App, HttpResponse};
|
||||
@ -154,6 +155,26 @@ mod tests {
|
||||
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]
|
||||
fn test_route_data_extractor() {
|
||||
let mut srv =
|
||||
|
17
src/error.rs
17
src/error.rs
@ -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
|
||||
#[derive(Debug, Display, From)]
|
||||
pub enum QueryPayloadError {
|
||||
|
10
src/lib.rs
10
src/lib.rs
@ -66,15 +66,15 @@
|
||||
//!
|
||||
//! ## Package feature
|
||||
//!
|
||||
//! * `client` - enables http client
|
||||
//! * `client` - enables http client (default enabled)
|
||||
//! * `ssl` - enables ssl support via `openssl` 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
|
||||
//! dependency
|
||||
//! * `brotli` - enables `brotli` compression support, requires `c`
|
||||
//! compiler
|
||||
//! compiler (default enabled)
|
||||
//! * `flate2-zlib` - enables `gzip`, `deflate` compression support, requires
|
||||
//! `c` compiler
|
||||
//! `c` compiler (default enabled)
|
||||
//! * `flate2-rust` - experimental rust based implementation for
|
||||
//! `gzip`, `deflate` compression.
|
||||
//!
|
||||
@ -111,7 +111,7 @@ pub use actix_web_codegen::*;
|
||||
|
||||
// re-export for convenience
|
||||
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::extract::FromRequest;
|
||||
@ -143,7 +143,7 @@ pub mod dev {
|
||||
pub use crate::types::json::JsonBody;
|
||||
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::ResponseBuilder as HttpResponseBuilder;
|
||||
pub use actix_http::{
|
||||
|
@ -2,7 +2,6 @@
|
||||
mod compress;
|
||||
pub use self::compress::{BodyEncoding, Compress};
|
||||
|
||||
pub mod cors;
|
||||
mod defaultheaders;
|
||||
pub mod errhandlers;
|
||||
mod logger;
|
||||
@ -12,5 +11,16 @@ pub use self::defaultheaders::DefaultHeaders;
|
||||
pub use self::logger::Logger;
|
||||
pub use self::normalize::NormalizePath;
|
||||
|
||||
#[cfg(feature = "secure-cookies")]
|
||||
pub mod identity;
|
||||
#[cfg(feature = "deprecated")]
|
||||
#[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;
|
||||
|
@ -38,7 +38,8 @@ impl ResourceMap {
|
||||
pub(crate) fn finish(&self, current: Rc<ResourceMap>) {
|
||||
for (_, nested) in &self.patterns {
|
||||
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>,
|
||||
{
|
||||
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) {
|
||||
Ok(Some(()))
|
||||
} else {
|
||||
|
135
src/scope.rs
135
src/scope.rs
@ -11,6 +11,7 @@ use actix_service::{
|
||||
use futures::future::{ok, Either, Future, FutureResult};
|
||||
use futures::{Async, IntoFuture, Poll};
|
||||
|
||||
use crate::config::ServiceConfig;
|
||||
use crate::data::Data;
|
||||
use crate::dev::{AppService, HttpServiceFactory};
|
||||
use crate::error::Error;
|
||||
@ -66,6 +67,7 @@ pub struct Scope<T = ScopeEndpoint> {
|
||||
services: Vec<Box<ServiceFactory>>,
|
||||
guards: Vec<Box<Guard>>,
|
||||
default: Rc<RefCell<Option<Rc<HttpNewService>>>>,
|
||||
external: Vec<ResourceDef>,
|
||||
factory_ref: Rc<RefCell<Option<ScopeFactory>>>,
|
||||
}
|
||||
|
||||
@ -80,6 +82,7 @@ impl Scope {
|
||||
guards: Vec::new(),
|
||||
services: Vec::new(),
|
||||
default: Rc::new(RefCell::new(None)),
|
||||
external: Vec::new(),
|
||||
factory_ref: fref,
|
||||
}
|
||||
}
|
||||
@ -153,6 +156,56 @@ where
|
||||
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.
|
||||
///
|
||||
/// This is similar to `App's` service registration.
|
||||
@ -281,6 +334,7 @@ where
|
||||
guards: self.guards,
|
||||
services: self.services,
|
||||
default: self.default,
|
||||
external: self.external,
|
||||
factory_ref: self.factory_ref,
|
||||
}
|
||||
}
|
||||
@ -359,6 +413,11 @@ where
|
||||
|
||||
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
|
||||
if let Some(ref mut ext) = self.data {
|
||||
config.set_service_data(ext);
|
||||
@ -594,7 +653,7 @@ mod tests {
|
||||
use crate::dev::{Body, ResponseBody};
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
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};
|
||||
|
||||
#[test]
|
||||
@ -1022,4 +1081,78 @@ mod tests {
|
||||
let resp = call_service(&mut srv, req);
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
46
src/test.rs
46
src/test.rs
@ -7,7 +7,7 @@ use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
|
||||
use actix_http::test::TestRequest as HttpTestRequest;
|
||||
use actix_http::{cookie::Cookie, Extensions, Request};
|
||||
use actix_router::{Path, ResourceDef, Url};
|
||||
use actix_rt::Runtime;
|
||||
use actix_rt::{System, SystemRunner};
|
||||
use actix_server_config::ServerConfig;
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
@ -29,14 +29,14 @@ use crate::{Error, HttpRequest, HttpResponse};
|
||||
|
||||
thread_local! {
|
||||
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 {
|
||||
fn get_mut(&mut self) -> &mut Runtime {
|
||||
fn get_mut(&mut self) -> &mut SystemRunner {
|
||||
self.0.as_mut().unwrap()
|
||||
}
|
||||
}
|
||||
@ -714,4 +714,42 @@ mod tests {
|
||||
let res = block_fn(|| app.call(req)).unwrap();
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
@ -175,15 +175,15 @@ where
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||
let req2 = req.clone();
|
||||
let (limit, err) = req
|
||||
let (limit, err, ctype) = req
|
||||
.app_data::<Self::Config>()
|
||||
.map(|c| (c.limit, c.ehandler.clone()))
|
||||
.unwrap_or((32768, None));
|
||||
.map(|c| (c.limit, c.ehandler.clone(), c.content_type.clone()))
|
||||
.unwrap_or((32768, None, None));
|
||||
|
||||
let path = req.path().to_string();
|
||||
|
||||
Box::new(
|
||||
JsonBody::new(req, payload)
|
||||
JsonBody::new(req, payload, ctype)
|
||||
.limit(limit)
|
||||
.map_err(move |e| {
|
||||
log::debug!(
|
||||
@ -224,6 +224,9 @@ where
|
||||
/// // change json extractor configuration
|
||||
/// web::Json::<Info>::configure(|cfg| {
|
||||
/// cfg.limit(4096)
|
||||
/// .content_type(|mime| { // <- accept text/plain content type
|
||||
/// mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN
|
||||
/// })
|
||||
/// .error_handler(|err, req| { // <- create custom error response
|
||||
/// error::InternalError::from_response(
|
||||
/// err, HttpResponse::Conflict().finish()).into()
|
||||
@ -237,6 +240,7 @@ where
|
||||
pub struct JsonConfig {
|
||||
limit: usize,
|
||||
ehandler: Option<Arc<dyn Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync>>,
|
||||
content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl JsonConfig {
|
||||
@ -254,6 +258,15 @@ impl JsonConfig {
|
||||
self.ehandler = Some(Arc::new(f));
|
||||
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 {
|
||||
@ -261,6 +274,7 @@ impl Default for JsonConfig {
|
||||
JsonConfig {
|
||||
limit: 32768,
|
||||
ehandler: None,
|
||||
content_type: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -271,6 +285,7 @@ impl Default for JsonConfig {
|
||||
/// Returns error:
|
||||
///
|
||||
/// * content type is not `application/json`
|
||||
/// (unless specified in [`JsonConfig`](struct.JsonConfig.html))
|
||||
/// * content length is greater than 256k
|
||||
pub struct JsonBody<U> {
|
||||
limit: usize,
|
||||
@ -285,13 +300,20 @@ where
|
||||
U: DeserializeOwned + 'static,
|
||||
{
|
||||
/// 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
|
||||
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 {
|
||||
false
|
||||
};
|
||||
|
||||
if !json {
|
||||
return JsonBody {
|
||||
limit: 262_144,
|
||||
@ -512,7 +534,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_json_body() {
|
||||
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));
|
||||
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
@ -521,7 +543,7 @@ mod tests {
|
||||
header::HeaderValue::from_static("application/text"),
|
||||
)
|
||||
.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));
|
||||
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
@ -535,7 +557,7 @@ mod tests {
|
||||
)
|
||||
.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));
|
||||
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
@ -550,7 +572,7 @@ mod tests {
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.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!(
|
||||
json.ok().unwrap(),
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
@ -9,6 +9,6 @@ pub(crate) mod readlines;
|
||||
|
||||
pub use self::form::{Form, FormConfig};
|
||||
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::query::{Query, QueryConfig};
|
||||
|
@ -1,5 +1,6 @@
|
||||
//! Path extractor
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::{fmt, ops};
|
||||
|
||||
use actix_http::error::{Error, ErrorNotFound};
|
||||
@ -7,6 +8,7 @@ use actix_router::PathDeserializer;
|
||||
use serde::de;
|
||||
|
||||
use crate::dev::Payload;
|
||||
use crate::error::PathError;
|
||||
use crate::request::HttpRequest;
|
||||
use crate::FromRequest;
|
||||
|
||||
@ -156,15 +158,89 @@ impl<T> FromRequest for Path<T>
|
||||
where
|
||||
T: de::DeserializeOwned,
|
||||
{
|
||||
type Config = ();
|
||||
type Error = Error;
|
||||
type Future = Result<Self, Error>;
|
||||
type Config = PathConfig;
|
||||
|
||||
#[inline]
|
||||
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()))
|
||||
.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 crate::test::{block_on, TestRequest};
|
||||
use crate::{error, http, HttpResponse};
|
||||
|
||||
#[derive(Deserialize, Debug, Display)]
|
||||
#[display(fmt = "MyStruct({}, {})", key, value)]
|
||||
@ -271,4 +348,21 @@ mod tests {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,13 @@
|
||||
# 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
|
||||
|
||||
* Update awc and actix-http deps
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-http-test"
|
||||
version = "0.2.0"
|
||||
version = "0.2.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix http test server"
|
||||
readme = "README.md"
|
||||
@ -32,10 +32,10 @@ ssl = ["openssl", "actix-server/ssl", "awc/ssl"]
|
||||
[dependencies]
|
||||
actix-codec = "0.1.2"
|
||||
actix-rt = "0.2.2"
|
||||
actix-service = "0.4.0"
|
||||
actix-server = "0.5.0"
|
||||
actix-utils = "0.4.0"
|
||||
awc = "0.2.0"
|
||||
actix-service = "0.4.1"
|
||||
actix-server = "0.5.1"
|
||||
actix-utils = "0.4.1"
|
||||
awc = "0.2.1"
|
||||
|
||||
base64 = "0.10"
|
||||
bytes = "0.4"
|
||||
@ -55,5 +55,5 @@ tokio-timer = "0.2"
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-web = "1.0.0-beta.4"
|
||||
actix-http = "0.2.0"
|
||||
actix-web = "1.0.0"
|
||||
actix-http = "0.2.4"
|
||||
|
1
test-server/LICENSE-APACHE
Symbolic link
1
test-server/LICENSE-APACHE
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
test-server/LICENSE-MIT
Symbolic link
1
test-server/LICENSE-MIT
Symbolic link
@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@ -255,6 +255,16 @@ impl TestServerRuntime {
|
||||
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
|
||||
pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest {
|
||||
self.client.request(method, path.as_ref())
|
||||
|
Reference in New Issue
Block a user