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

Compare commits

...

19 Commits

Author SHA1 Message Date
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
46 changed files with 438 additions and 72 deletions

View File

@ -1,20 +1,26 @@
# Changes # Changes
## [1.0.0] - 2019-05-xx ## [1.0.0] - 2019-06-05
### Add ### Add
* Add `Scope::configure()` method.
* Add `ServiceRequest::set_payload()` method. * Add `ServiceRequest::set_payload()` method.
* Add `test::TestRequest::set_json()` convenience method to automatically * Add `test::TestRequest::set_json()` convenience method to automatically
serialize data and set header in test requests. serialize data and set header in test requests.
* Add macros for head, options, trace, connect and patch http methods
### Changes ### Changes
* Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863 * Drop an unnecessary `Option<_>` indirection around `ServerBuilder` from `HttpServer`. #863
### Fixed ### Fixed
* Fix Logger request time format, and use rfc3339. #867
* Clear http requests pool on app service drop #860 * Clear http requests pool on app service drop #860

View File

@ -72,11 +72,11 @@ actix-service = "0.4.0"
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.3"
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.0", optional = true }
bytes = "0.4" bytes = "0.4"
@ -100,9 +100,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-http = { version = "0.2.3", features=["ssl", "brotli", "flate2-zlib"] }
actix-http-test = { version = "0.2.0", features=["ssl"] } actix-http-test = { version = "0.2.0", features=["ssl"] }
actix-files = { version = "0.1.0" } actix-files = { version = "0.1.1" }
rand = "0.6" rand = "0.6"
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"

View File

@ -1,5 +1,9 @@
# Changes # Changes
## [0.1.1] - 2019-06-01
* Static files are incorrectly served as both chunked and with length #812
## [0.1.0] - 2019-05-25 ## [0.1.0] - 2019-05-25
* NamedFile last-modified check always fails due to nano-seconds * NamedFile last-modified check always fails due to nano-seconds

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-files" name = "actix-files"
version = "0.1.0" version = "0.1.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Static files support for actix web." description = "Static files support for actix web."
readme = "README.md" readme = "README.md"
@ -19,6 +19,7 @@ path = "src/lib.rs"
[dependencies] [dependencies]
actix-web = "1.0.0-rc" actix-web = "1.0.0-rc"
actix-http = "0.2.3"
actix-service = "0.4.0" actix-service = "0.4.0"
bitflags = "1" bitflags = "1"
bytes = "0.4" bytes = "0.4"

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

@ -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,
}; };
@ -434,7 +435,7 @@ impl Responder for NamedFile {
if offset != 0 || length != self.md.len() { if offset != 0 || length != self.md.len() {
return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader)); return Ok(resp.status(StatusCode::PARTIAL_CONTENT).streaming(reader));
}; };
Ok(resp.streaming(reader)) Ok(resp.body(SizedStream::new(length, reader)))
} }
} }
} }

View File

@ -1,5 +1,18 @@
# Changes # Changes
## [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 ## [0.2.2] - 2019-05-29
### Fixed ### Fixed

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-http" name = "actix-http"
version = "0.2.2" version = "0.2.3"
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"
@ -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

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

@ -12,7 +12,6 @@ use futures::stream::{once, Stream};
use regex::Regex; 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,
@ -218,30 +217,28 @@ fn test_expect_continue_h1() {
#[test] #[test]
fn test_chunked_payload() { 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 total_size: usize = chunk_sizes.iter().sum();
let srv = TestServer::new(|| { let srv = TestServer::new(|| {
HttpService::build() HttpService::build().h1(|mut request: Request| {
.h1(|mut request: Request| { request
request.take_payload() .take_payload()
.map_err(|e| panic!(format!("Error reading payload: {}", e))) .map_err(|e| panic!(format!("Error reading payload: {}", e)))
.fold(0usize, |acc, chunk| { .fold(0usize, |acc, chunk| future::ok::<_, ()>(acc + chunk.len()))
future::ok::<_, ()>(acc + chunk.len()) .map(|req_size| Response::Ok().body(format!("size={}", req_size)))
}) })
.map(|req_size| {
Response::Ok().body(format!("size={}", req_size))
})
})
}); });
let returned_size = { let returned_size = {
let mut stream = net::TcpStream::connect(srv.addr()).unwrap(); 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() { for chunk_size in chunk_sizes.iter() {
let mut bytes = Vec::new(); 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(format!("{:X}\r\n", chunk_size).as_bytes());
bytes.extend(&random_bytes[..]); bytes.extend(&random_bytes[..]);
@ -826,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))),
) )
}) })
}); });
@ -852,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

@ -1,5 +1,9 @@
# Changes # Changes
## [0.1.2] - 2019-06-02
* Fix boundary parsing #876
## [0.1.1] - 2019-05-25 ## [0.1.1] - 2019-05-25
* Fix disconnect handling #834 * Fix disconnect handling #834

View File

@ -1,6 +1,6 @@
[package] [package]
name = "actix-multipart" name = "actix-multipart"
version = "0.1.1" version = "0.1.2"
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"
@ -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.2"

View File

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

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

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

View File

@ -537,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;
} }
} }
} }
@ -576,7 +574,7 @@ impl InnerField {
} }
} }
} else { } else {
return Ok(Async::Ready(Some(payload.buf.take().freeze()))); Ok(Async::Ready(Some(payload.buf.take().freeze())))
}; };
} }
} }

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"

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-rc"
actix-http = "0.2.0" actix-http = "0.2.2"
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-rc" }
actix-http = { version = "0.2.0", features=["ssl"] } actix-http = { version = "0.2.2", 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::{delete, get, post, put, patch, head, connect, options, 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"
@ -41,7 +41,7 @@ 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.0"
actix-http = "0.2.0" actix-http = "0.2.3"
base64 = "0.10.1" base64 = "0.10.1"
bytes = "0.4" bytes = "0.4"
derive_more = "0.14" derive_more = "0.14"
@ -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-rc", features=["ssl"] }
actix-http = { version = "0.2.0", features=["ssl"] } actix-http = { version = "0.2.3", 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

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

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

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

@ -122,7 +122,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,58 @@ 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"[..]);
}
} }

View File

@ -1,5 +1,9 @@
# Changes # Changes
## [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.1"
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-rc"
actix-http = "0.2.0" actix-http = "0.2.3"

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