mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-15 06:26:11 +02:00
Compare commits
39 Commits
Author | SHA1 | Date | |
---|---|---|---|
d6787e6c56 | |||
b9d870645f | |||
ef89430f9b | |||
953a0d4e4a | |||
5ea2d68438 | |||
d65a03f6ac | |||
b588b2bf5c | |||
d455e2cd13 | |||
9306631d6e | |||
f735da504b | |||
487a713ca0 | |||
095ad328ee | |||
a38afa0cec | |||
9619698543 | |||
4b1a471b35 | |||
b6039b0bff | |||
d8fa43034f | |||
92f993e054 | |||
c172deb0f3 | |||
dee6aed010 | |||
76f021a6e3 | |||
2f244ea028 | |||
5f5ddc8f01 | |||
8b473745cb | |||
18575ee1ee | |||
e58b38fd13 | |||
b043c34632 | |||
b748bf3b0d | |||
be12d5e6fc | |||
7c4941f868 | |||
d1f5c457c4 | |||
c26c5fd9a4 | |||
4a73d1c8c1 | |||
7c395fcc83 | |||
54c33a7aff | |||
47d80382b2 | |||
ba816a8562 | |||
6f75b0e95e | |||
b3cc43bb9b |
@ -31,13 +31,13 @@ environment:
|
||||
CHANNEL: beta
|
||||
# Nightly channel
|
||||
- TARGET: i686-pc-windows-gnu
|
||||
CHANNEL: nightly-2017-12-21
|
||||
CHANNEL: nightly
|
||||
- TARGET: i686-pc-windows-msvc
|
||||
CHANNEL: nightly-2017-12-21
|
||||
CHANNEL: nightly
|
||||
- TARGET: x86_64-pc-windows-gnu
|
||||
CHANNEL: nightly-2017-12-21
|
||||
CHANNEL: nightly
|
||||
- TARGET: x86_64-pc-windows-msvc
|
||||
CHANNEL: nightly-2017-12-21
|
||||
CHANNEL: nightly
|
||||
|
||||
# Install Rust and Cargo
|
||||
# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml)
|
||||
|
@ -38,7 +38,7 @@ script:
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "beta" ]]; then
|
||||
bash <(curl https://raw.githubusercontent.com/xd009642/tarpaulin/master/travis-install.sh)
|
||||
USE_SKEPTIC=1 cargo tarpaulin --out Xml
|
||||
USE_SKEPTIC=1 cargo tarpaulin --out Xml --no-count
|
||||
bash <(curl -s https://codecov.io/bash)
|
||||
echo "Uploaded code coverage"
|
||||
fi
|
||||
|
35
CHANGES.md
35
CHANGES.md
@ -1,5 +1,40 @@
|
||||
# Changes
|
||||
|
||||
## 0.6.5 (2018-05-15)
|
||||
|
||||
* Fix error handling during request decoding #222
|
||||
|
||||
|
||||
## 0.6.4 (2018-05-11)
|
||||
|
||||
* Fix segfault in ServerSettings::get_response_builder()
|
||||
|
||||
|
||||
## 0.6.3 (2018-05-10)
|
||||
|
||||
* Add `Router::with_async()` method for async handler registration.
|
||||
|
||||
* Added error response functions for 501,502,503,504
|
||||
|
||||
* Fix client request timeout handling
|
||||
|
||||
|
||||
## 0.6.2 (2018-05-09)
|
||||
|
||||
* WsWriter trait is optional.
|
||||
|
||||
|
||||
## 0.6.1 (2018-05-08)
|
||||
|
||||
* Fix http/2 payload streaming #215
|
||||
|
||||
* Fix connector's default `keep-alive` and `lifetime` settings #212
|
||||
|
||||
* Send `ErrorNotFound` instead of `ErrorBadRequest` when path extractor fails #214
|
||||
|
||||
* Allow to exclude certain endpoints from logging #211
|
||||
|
||||
|
||||
## 0.6.0 (2018-05-08)
|
||||
|
||||
* Add route scopes #202
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "0.6.0"
|
||||
version = "0.6.5"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix web is a simple, pragmatic and extremely fast web framework for Rust."
|
||||
readme = "README.md"
|
||||
|
18
MIGRATION.md
18
MIGRATION.md
@ -1,5 +1,7 @@
|
||||
## Migration from 0.5 to 0.6
|
||||
|
||||
* `Path<T>` extractor return `ErrorNotFound` on failure instead of `ErrorBadRequest`
|
||||
|
||||
* `ws::Message::Close` now includes optional close reason.
|
||||
`ws::CloseCode::Status` and `ws::CloseCode::Empty` have been removed.
|
||||
|
||||
@ -11,6 +13,17 @@
|
||||
* `HttpRequest::extensions()` returns read only reference to the request's Extension
|
||||
`HttpRequest::extensions_mut()` returns mutable reference.
|
||||
|
||||
* Instead of
|
||||
|
||||
`use actix_web::middleware::{
|
||||
CookieSessionBackend, CookieSessionError, RequestSession,
|
||||
Session, SessionBackend, SessionImpl, SessionStorage};`
|
||||
|
||||
use `actix_web::middleware::session`
|
||||
|
||||
`use actix_web::middleware::session{CookieSessionBackend, CookieSessionError,
|
||||
RequestSession, Session, SessionBackend, SessionImpl, SessionStorage};`
|
||||
|
||||
* `FromRequest::from_request()` accepts mutable reference to a request
|
||||
|
||||
* `FromRequest::Result` has to implement `Into<Reply<Self>>`
|
||||
@ -19,7 +32,7 @@
|
||||
https://actix.rs/actix-web/actix_web/trait.Responder.html#tymethod.respond_to)
|
||||
is generic over `S`
|
||||
|
||||
* `HttpRequest::query()` is deprecated. Use `Query` extractor.
|
||||
* Use `Query` extractor instead of HttpRequest::query()`.
|
||||
|
||||
```rust
|
||||
fn index(q: Query<HashMap<String, String>>) -> Result<..> {
|
||||
@ -33,6 +46,9 @@
|
||||
let q = Query::<HashMap<String, String>>::extract(req);
|
||||
```
|
||||
|
||||
* Websocket operations are implemented as `WsWriter` trait.
|
||||
you need to use `use actix_web::ws::WsWriter`
|
||||
|
||||
|
||||
## Migration from 0.4 to 0.5
|
||||
|
||||
|
@ -18,6 +18,7 @@ Actix web is a simple, pragmatic and extremely fast web framework for Rust.
|
||||
[DefaultHeaders](https://actix.rs/book/actix-web/sec-9-middlewares.html#default-headers),
|
||||
[CORS](https://actix.rs/actix-web/actix_web/middleware/cors/index.html),
|
||||
[CSRF](https://actix.rs/actix-web/actix_web/middleware/csrf/index.html))
|
||||
* Includes an asynchronous [HTTP client](https://github.com/actix/actix-web/blob/master/src/client/mod.rs)
|
||||
* Built on top of [Actix actor framework](https://github.com/actix/actix)
|
||||
|
||||
## Documentation & community resources
|
||||
@ -36,7 +37,7 @@ extern crate actix_web;
|
||||
use actix_web::{http, server, App, Path};
|
||||
|
||||
fn index(info: Path<(u32, String)>) -> String {
|
||||
format!("Hello {}! id:{}", info.0, info.1)
|
||||
format!("Hello {}! id:{}", info.1, info.0)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
9
build.rs
9
build.rs
@ -1,8 +1,15 @@
|
||||
extern crate version_check;
|
||||
|
||||
fn main() {
|
||||
match version_check::is_min_version("1.26.0") {
|
||||
Some((true, _)) => println!("cargo:rustc-cfg=actix_impl_trait"),
|
||||
_ => (),
|
||||
};
|
||||
match version_check::is_nightly() {
|
||||
Some(true) => println!("cargo:rustc-cfg=actix_nightly"),
|
||||
Some(true) => {
|
||||
println!("cargo:rustc-cfg=actix_nightly");
|
||||
println!("cargo:rustc-cfg=actix_impl_trait");
|
||||
}
|
||||
Some(false) => (),
|
||||
None => (),
|
||||
};
|
||||
|
@ -223,8 +223,8 @@ impl Default for ClientConnector {
|
||||
pool: Rc::new(Pool::new(Rc::clone(&_modified))),
|
||||
pool_modified: _modified,
|
||||
connector: builder.build().unwrap(),
|
||||
conn_lifetime: Duration::from_secs(15),
|
||||
conn_keep_alive: Duration::from_secs(75),
|
||||
conn_lifetime: Duration::from_secs(75),
|
||||
conn_keep_alive: Duration::from_secs(15),
|
||||
limit: 100,
|
||||
limit_per_host: 0,
|
||||
acquired: 0,
|
||||
@ -243,8 +243,8 @@ impl Default for ClientConnector {
|
||||
subscriber: None,
|
||||
pool: Rc::new(Pool::new(Rc::clone(&_modified))),
|
||||
pool_modified: _modified,
|
||||
conn_lifetime: Duration::from_secs(15),
|
||||
conn_keep_alive: Duration::from_secs(75),
|
||||
conn_lifetime: Duration::from_secs(75),
|
||||
conn_keep_alive: Duration::from_secs(15),
|
||||
limit: 100,
|
||||
limit_per_host: 0,
|
||||
acquired: 0,
|
||||
|
@ -49,6 +49,7 @@ use httpresponse::HttpResponse;
|
||||
impl ResponseError for SendRequestError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match *self {
|
||||
SendRequestError::Timeout => HttpResponse::GatewayTimeout(),
|
||||
SendRequestError::Connector(_) => HttpResponse::BadGateway(),
|
||||
_ => HttpResponse::InternalServerError(),
|
||||
}.into()
|
||||
|
@ -194,6 +194,7 @@ impl Future for SendRequest {
|
||||
self.state = State::Send(pl);
|
||||
}
|
||||
State::Send(mut pl) => {
|
||||
pl.poll_timeout()?;
|
||||
pl.poll_write().map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("{}", e).as_str())
|
||||
})?;
|
||||
@ -315,7 +316,7 @@ impl Pipeline {
|
||||
{
|
||||
Async::NotReady => need_run = true,
|
||||
Async::Ready(_) => {
|
||||
let _ = self.poll_timeout().map_err(|e| {
|
||||
self.poll_timeout().map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("{}", e))
|
||||
})?;
|
||||
}
|
||||
@ -371,16 +372,15 @@ impl Pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_timeout(&mut self) -> Poll<(), SendRequestError> {
|
||||
fn poll_timeout(&mut self) -> Result<(), SendRequestError> {
|
||||
if self.timeout.is_some() {
|
||||
match self.timeout.as_mut().unwrap().poll() {
|
||||
Ok(Async::Ready(())) => Err(SendRequestError::Timeout),
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Ok(Async::Ready(())) => return Err(SendRequestError::Timeout),
|
||||
Ok(Async::NotReady) => (),
|
||||
Err(_) => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
88
src/error.rs
88
src/error.rs
@ -757,6 +757,46 @@ where
|
||||
InternalError::new(err, StatusCode::INTERNAL_SERVER_ERROR).into()
|
||||
}
|
||||
|
||||
/// Helper function that creates wrapper of any error and
|
||||
/// generate *NOT IMPLEMENTED* response.
|
||||
#[allow(non_snake_case)]
|
||||
pub fn ErrorNotImplemented<T>(err: T) -> Error
|
||||
where
|
||||
T: Send + Sync + fmt::Debug + fmt::Display + 'static,
|
||||
{
|
||||
InternalError::new(err, StatusCode::NOT_IMPLEMENTED).into()
|
||||
}
|
||||
|
||||
/// Helper function that creates wrapper of any error and
|
||||
/// generate *BAD GATEWAY* response.
|
||||
#[allow(non_snake_case)]
|
||||
pub fn ErrorBadGateway<T>(err: T) -> Error
|
||||
where
|
||||
T: Send + Sync + fmt::Debug + fmt::Display + 'static,
|
||||
{
|
||||
InternalError::new(err, StatusCode::BAD_GATEWAY).into()
|
||||
}
|
||||
|
||||
/// Helper function that creates wrapper of any error and
|
||||
/// generate *SERVICE UNAVAILABLE* response.
|
||||
#[allow(non_snake_case)]
|
||||
pub fn ErrorServiceUnavailable<T>(err: T) -> Error
|
||||
where
|
||||
T: Send + Sync + fmt::Debug + fmt::Display + 'static,
|
||||
{
|
||||
InternalError::new(err, StatusCode::SERVICE_UNAVAILABLE).into()
|
||||
}
|
||||
|
||||
/// Helper function that creates wrapper of any error and
|
||||
/// generate *GATEWAY TIMEOUT* response.
|
||||
#[allow(non_snake_case)]
|
||||
pub fn ErrorGatewayTimeout<T>(err: T) -> Error
|
||||
where
|
||||
T: Send + Sync + fmt::Debug + fmt::Display + 'static,
|
||||
{
|
||||
InternalError::new(err, StatusCode::GATEWAY_TIMEOUT).into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@ -912,4 +952,52 @@ mod tests {
|
||||
let resp: HttpResponse = err.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_error_helpers() {
|
||||
let r: HttpResponse = ErrorBadRequest("err").into();
|
||||
assert_eq!(r.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
let r: HttpResponse = ErrorUnauthorized("err").into();
|
||||
assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
|
||||
|
||||
let r: HttpResponse = ErrorForbidden("err").into();
|
||||
assert_eq!(r.status(), StatusCode::FORBIDDEN);
|
||||
|
||||
let r: HttpResponse = ErrorNotFound("err").into();
|
||||
assert_eq!(r.status(), StatusCode::NOT_FOUND);
|
||||
|
||||
let r: HttpResponse = ErrorMethodNotAllowed("err").into();
|
||||
assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED);
|
||||
|
||||
let r: HttpResponse = ErrorRequestTimeout("err").into();
|
||||
assert_eq!(r.status(), StatusCode::REQUEST_TIMEOUT);
|
||||
|
||||
let r: HttpResponse = ErrorConflict("err").into();
|
||||
assert_eq!(r.status(), StatusCode::CONFLICT);
|
||||
|
||||
let r: HttpResponse = ErrorGone("err").into();
|
||||
assert_eq!(r.status(), StatusCode::GONE);
|
||||
|
||||
let r: HttpResponse = ErrorPreconditionFailed("err").into();
|
||||
assert_eq!(r.status(), StatusCode::PRECONDITION_FAILED);
|
||||
|
||||
let r: HttpResponse = ErrorExpectationFailed("err").into();
|
||||
assert_eq!(r.status(), StatusCode::EXPECTATION_FAILED);
|
||||
|
||||
let r: HttpResponse = ErrorInternalServerError("err").into();
|
||||
assert_eq!(r.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
|
||||
let r: HttpResponse = ErrorNotImplemented("err").into();
|
||||
assert_eq!(r.status(), StatusCode::NOT_IMPLEMENTED);
|
||||
|
||||
let r: HttpResponse = ErrorBadGateway("err").into();
|
||||
assert_eq!(r.status(), StatusCode::BAD_GATEWAY);
|
||||
|
||||
let r: HttpResponse = ErrorServiceUnavailable("err").into();
|
||||
assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
|
||||
let r: HttpResponse = ErrorGatewayTimeout("err").into();
|
||||
assert_eq!(r.status(), StatusCode::GATEWAY_TIMEOUT);
|
||||
}
|
||||
}
|
||||
|
@ -11,7 +11,7 @@ use serde::de::{self, DeserializeOwned};
|
||||
use serde_urlencoded;
|
||||
|
||||
use de::PathDeserializer;
|
||||
use error::{Error, ErrorBadRequest};
|
||||
use error::{Error, ErrorNotFound, ErrorBadRequest};
|
||||
use handler::{AsyncResult, FromRequest};
|
||||
use httpmessage::{HttpMessage, MessageBody, UrlEncoded};
|
||||
use httprequest::HttpRequest;
|
||||
@ -108,7 +108,7 @@ where
|
||||
fn from_request(req: &HttpRequest<S>, _: &Self::Config) -> Self::Result {
|
||||
let req = req.clone();
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&req))
|
||||
.map_err(|e| e.into())
|
||||
.map_err(ErrorNotFound)
|
||||
.map(|inner| Path { inner })
|
||||
}
|
||||
}
|
||||
|
@ -492,14 +492,15 @@ where
|
||||
/// }
|
||||
///
|
||||
/// /// extract path info using serde
|
||||
/// fn index(state: State<MyApp>, info: Path<Info>) -> String {
|
||||
/// format!("{} {}!", state.msg, info.username)
|
||||
/// fn index(data: (State<MyApp>, Path<Info>)) -> String {
|
||||
/// let (state, path) = data;
|
||||
/// format!("{} {}!", state.msg, path.username)
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::with_state(MyApp{msg: "Welcome"}).resource(
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with2(index)); // <- use `with` extractor
|
||||
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
pub struct State<S>(HttpRequest<S>);
|
||||
|
@ -27,7 +27,6 @@ use uri::Url as InnerUrl;
|
||||
|
||||
bitflags! {
|
||||
pub(crate) struct MessageFlags: u8 {
|
||||
const QUERY = 0b0000_0001;
|
||||
const KEEPALIVE = 0b0000_0010;
|
||||
}
|
||||
}
|
||||
@ -40,8 +39,6 @@ pub struct HttpInnerMessage {
|
||||
pub headers: HeaderMap,
|
||||
pub extensions: Extensions,
|
||||
pub params: Params<'static>,
|
||||
pub cookies: Option<Vec<Cookie<'static>>>,
|
||||
pub query: Params<'static>,
|
||||
pub addr: Option<SocketAddr>,
|
||||
pub payload: Option<Payload>,
|
||||
pub info: Option<ConnectionInfo<'static>>,
|
||||
@ -49,6 +46,9 @@ pub struct HttpInnerMessage {
|
||||
resource: RouterResource,
|
||||
}
|
||||
|
||||
struct Query(Params<'static>);
|
||||
struct Cookies(Vec<Cookie<'static>>);
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
enum RouterResource {
|
||||
Notset,
|
||||
@ -64,9 +64,7 @@ impl Default for HttpInnerMessage {
|
||||
headers: HeaderMap::with_capacity(16),
|
||||
flags: MessageFlags::empty(),
|
||||
params: Params::new(),
|
||||
query: Params::new(),
|
||||
addr: None,
|
||||
cookies: None,
|
||||
payload: None,
|
||||
extensions: Extensions::new(),
|
||||
info: None,
|
||||
@ -91,7 +89,6 @@ impl HttpInnerMessage {
|
||||
self.addr = None;
|
||||
self.info = None;
|
||||
self.flags = MessageFlags::empty();
|
||||
self.cookies = None;
|
||||
self.payload = None;
|
||||
self.prefix = 0;
|
||||
self.resource = RouterResource::Notset;
|
||||
@ -109,7 +106,10 @@ impl HttpRequest<()> {
|
||||
/// Construct a new Request.
|
||||
#[inline]
|
||||
pub fn new(
|
||||
method: Method, uri: Uri, version: Version, headers: HeaderMap,
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
version: Version,
|
||||
headers: HeaderMap,
|
||||
payload: Option<Payload>,
|
||||
) -> HttpRequest {
|
||||
let url = InnerUrl::new(uri);
|
||||
@ -121,9 +121,7 @@ impl HttpRequest<()> {
|
||||
headers,
|
||||
payload,
|
||||
params: Params::new(),
|
||||
query: Params::new(),
|
||||
extensions: Extensions::new(),
|
||||
cookies: None,
|
||||
addr: None,
|
||||
info: None,
|
||||
prefix: 0,
|
||||
@ -306,7 +304,9 @@ impl<S> HttpRequest<S> {
|
||||
/// }
|
||||
/// ```
|
||||
pub fn url_for<U, I>(
|
||||
&self, name: &str, elements: U,
|
||||
&self,
|
||||
name: &str,
|
||||
elements: U,
|
||||
) -> Result<Url, UrlGenerationError>
|
||||
where
|
||||
U: IntoIterator<Item = I>,
|
||||
@ -369,20 +369,20 @@ impl<S> HttpRequest<S> {
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.6.0", note = "please use `Query<T>` extractor")]
|
||||
/// Get a reference to the Params object.
|
||||
/// Params is a container for url query parameters.
|
||||
pub fn query(&self) -> &Params {
|
||||
if !self.as_ref().flags.contains(MessageFlags::QUERY) {
|
||||
self.as_mut().flags.insert(MessageFlags::QUERY);
|
||||
let params: &mut Params =
|
||||
unsafe { mem::transmute(&mut self.as_mut().query) };
|
||||
params.clear();
|
||||
pub fn query<'a>(&'a self) -> &'a Params {
|
||||
if let None = self.extensions().get::<Query>() {
|
||||
let mut params: Params<'a> = Params::new();
|
||||
for (key, val) in form_urlencoded::parse(self.query_string().as_ref()) {
|
||||
params.add(key, val);
|
||||
}
|
||||
let params: Params<'static> = unsafe { mem::transmute(params) };
|
||||
self.as_mut().extensions.insert(Query(params));
|
||||
}
|
||||
unsafe { mem::transmute(&self.as_ref().query) }
|
||||
let params: &Params<'a> =
|
||||
unsafe { mem::transmute(&self.extensions().get::<Query>().unwrap().0) };
|
||||
params
|
||||
}
|
||||
|
||||
/// The query string in the URL.
|
||||
@ -399,7 +399,7 @@ impl<S> HttpRequest<S> {
|
||||
|
||||
/// Load request cookies.
|
||||
pub fn cookies(&self) -> Result<&Vec<Cookie<'static>>, CookieParseError> {
|
||||
if self.as_ref().cookies.is_none() {
|
||||
if let None = self.extensions().get::<Query>() {
|
||||
let msg = self.as_mut();
|
||||
let mut cookies = Vec::new();
|
||||
for hdr in msg.headers.get_all(header::COOKIE) {
|
||||
@ -410,9 +410,9 @@ impl<S> HttpRequest<S> {
|
||||
}
|
||||
}
|
||||
}
|
||||
msg.cookies = Some(cookies);
|
||||
msg.extensions.insert(Cookies(cookies));
|
||||
}
|
||||
Ok(&self.as_ref().cookies.as_ref().unwrap())
|
||||
Ok(&self.extensions().get::<Cookies>().unwrap().0)
|
||||
}
|
||||
|
||||
/// Return request cookie.
|
||||
@ -427,6 +427,12 @@ impl<S> HttpRequest<S> {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn set_cookies(&mut self, cookies: Option<Vec<Cookie<'static>>>) {
|
||||
if let Some(cookies) = cookies {
|
||||
self.extensions_mut().insert(Cookies(cookies));
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a reference to the Params object.
|
||||
///
|
||||
/// Params is a container for url parameters.
|
||||
@ -664,10 +670,8 @@ mod tests {
|
||||
|
||||
let mut resource = ResourceHandler::<()>::default();
|
||||
resource.name("index");
|
||||
let routes = vec![(
|
||||
Resource::new("index", "/user/{name}.{ext}"),
|
||||
Some(resource),
|
||||
)];
|
||||
let routes =
|
||||
vec![(Resource::new("index", "/user/{name}.{ext}"), Some(resource))];
|
||||
let (router, _) = Router::new("/", ServerSettings::default(), routes);
|
||||
assert!(router.has_route("/user/test.html"));
|
||||
assert!(!router.has_route("/test/unknown"));
|
||||
@ -696,10 +700,8 @@ mod tests {
|
||||
|
||||
let mut resource = ResourceHandler::<()>::default();
|
||||
resource.name("index");
|
||||
let routes = vec![(
|
||||
Resource::new("index", "/user/{name}.{ext}"),
|
||||
Some(resource),
|
||||
)];
|
||||
let routes =
|
||||
vec![(Resource::new("index", "/user/{name}.{ext}"), Some(resource))];
|
||||
let (router, _) = Router::new("/prefix/", ServerSettings::default(), routes);
|
||||
assert!(router.has_route("/user/test.html"));
|
||||
assert!(!router.has_route("/prefix/user/test.html"));
|
||||
|
24
src/lib.rs
24
src/lib.rs
@ -60,7 +60,21 @@
|
||||
//! * Middlewares (`Logger`, `Session`, `CORS`, `CSRF`, `DefaultHeaders`)
|
||||
//! * Built on top of [Actix actor framework](https://github.com/actix/actix)
|
||||
//! * Supported Rust version: 1.24 or later
|
||||
|
||||
//!
|
||||
//! ## Package feature
|
||||
//!
|
||||
//! * `tls` - enables ssl support via `native-tls` crate
|
||||
//! * `alpn` - enables ssl support via `openssl` crate, require for `http/2`
|
||||
//! support
|
||||
//! * `session` - enables session support, includes `ring` crate as
|
||||
//! dependency
|
||||
//! * `brotli` - enables `brotli` compression support, requires `c`
|
||||
//! compiler
|
||||
//! * `flate-c` - enables `gzip`, `deflate` compression support, requires
|
||||
//! `c` compiler
|
||||
//! * `flate-rust` - experimental rust based implementation for
|
||||
//! `gzip`, `deflate` compression.
|
||||
//!
|
||||
#![cfg_attr(actix_nightly, feature(
|
||||
specialization, // for impl ErrorResponse for std::error::Error
|
||||
))]
|
||||
@ -169,12 +183,17 @@ pub use body::{Binary, Body};
|
||||
pub use context::HttpContext;
|
||||
pub use error::{Error, ResponseError, Result};
|
||||
pub use extractor::{Form, Path, Query};
|
||||
pub use handler::{AsyncResponder, Either, FromRequest, FutureResponse, Responder, State};
|
||||
pub use handler::{
|
||||
AsyncResponder, Either, FromRequest, FutureResponse, Responder, State,
|
||||
};
|
||||
pub use httpmessage::HttpMessage;
|
||||
pub use httprequest::HttpRequest;
|
||||
pub use httpresponse::HttpResponse;
|
||||
pub use json::Json;
|
||||
pub use scope::Scope;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.6.2", note = "please use `use actix_web::ws::WsWriter`")]
|
||||
pub use ws::WsWriter;
|
||||
|
||||
#[cfg(feature = "openssl")]
|
||||
@ -210,6 +229,7 @@ pub mod dev {
|
||||
pub use resource::ResourceHandler;
|
||||
pub use route::Route;
|
||||
pub use router::{Resource, ResourceType, Router};
|
||||
pub use with::ExtractorConfig;
|
||||
}
|
||||
|
||||
pub mod http {
|
||||
|
@ -1,7 +1,7 @@
|
||||
//! Request logging middleware
|
||||
use std::collections::HashSet;
|
||||
use std::env;
|
||||
use std::fmt;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use libc;
|
||||
use regex::Regex;
|
||||
@ -74,6 +74,7 @@ use middleware::{Finished, Middleware, Started};
|
||||
///
|
||||
pub struct Logger {
|
||||
format: Format,
|
||||
exclude: HashSet<String>,
|
||||
}
|
||||
|
||||
impl Logger {
|
||||
@ -81,8 +82,15 @@ impl Logger {
|
||||
pub fn new(format: &str) -> Logger {
|
||||
Logger {
|
||||
format: Format::new(format),
|
||||
exclude: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ignore and do not log access info for specified path.
|
||||
pub fn exclude<T: Into<String>>(mut self, path: T) -> Self {
|
||||
self.exclude.insert(path.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Logger {
|
||||
@ -94,6 +102,7 @@ impl Default for Logger {
|
||||
fn default() -> Logger {
|
||||
Logger {
|
||||
format: Format::default(),
|
||||
exclude: HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -102,21 +111,23 @@ struct StartTime(time::Tm);
|
||||
|
||||
impl Logger {
|
||||
fn log<S>(&self, req: &mut HttpRequest<S>, resp: &HttpResponse) {
|
||||
let entry_time = req.extensions().get::<StartTime>().unwrap().0;
|
||||
|
||||
let render = |fmt: &mut Formatter| {
|
||||
for unit in &self.format.0 {
|
||||
unit.render(fmt, req, resp, entry_time)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
info!("{}", FormatDisplay(&render));
|
||||
if let Some(entry_time) = req.extensions().get::<StartTime>() {
|
||||
let render = |fmt: &mut Formatter| {
|
||||
for unit in &self.format.0 {
|
||||
unit.render(fmt, req, resp, entry_time.0)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
info!("{}", FormatDisplay(&render));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Middleware<S> for Logger {
|
||||
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
|
||||
req.extensions_mut().insert(StartTime(time::now()));
|
||||
if !self.exclude.contains(req.path()) {
|
||||
req.extensions_mut().insert(StartTime(time::now()));
|
||||
}
|
||||
Ok(Started::Done)
|
||||
}
|
||||
|
||||
|
@ -492,8 +492,8 @@ impl<S: 'static, H> ProcessResponse<S, H> {
|
||||
if let Some(err) = self.resp.error() {
|
||||
if self.resp.status().is_server_error() {
|
||||
error!(
|
||||
"Error occured during request handling: {}",
|
||||
err
|
||||
"Error occured during request handling, status: {} {}",
|
||||
self.resp.status(), err
|
||||
);
|
||||
} else {
|
||||
warn!(
|
||||
|
@ -1,9 +1,11 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use futures::Future;
|
||||
use http::{Method, StatusCode};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use error::Error;
|
||||
use handler::{AsyncResult, FromRequest, Handler, Responder};
|
||||
use httprequest::HttpRequest;
|
||||
use httpresponse::HttpResponse;
|
||||
@ -183,6 +185,25 @@ impl<S: 'static> ResourceHandler<S> {
|
||||
self.routes.last_mut().unwrap().with(handler);
|
||||
}
|
||||
|
||||
/// Register a new route and add async handler.
|
||||
///
|
||||
/// This is shortcut for:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// Application::resource("/", |r| r.route().with_async(index)
|
||||
/// ```
|
||||
pub fn with_async<T, F, R, I, E>(&mut self, handler: F)
|
||||
where
|
||||
F: Fn(T) -> R + 'static,
|
||||
R: Future<Item = I, Error = E> + 'static,
|
||||
I: Responder + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
T: FromRequest<S> + 'static,
|
||||
{
|
||||
self.routes.push(Route::default());
|
||||
self.routes.last_mut().unwrap().with_async(handler);
|
||||
}
|
||||
|
||||
/// Register a resource middleware
|
||||
///
|
||||
/// This is similar to `App's` middlewares, but
|
||||
|
74
src/route.rs
74
src/route.rs
@ -13,7 +13,7 @@ use httpresponse::HttpResponse;
|
||||
use middleware::{Finished as MiddlewareFinished, Middleware,
|
||||
Response as MiddlewareResponse, Started as MiddlewareStarted};
|
||||
use pred::Predicate;
|
||||
use with::{ExtractorConfig, With, With2, With3};
|
||||
use with::{ExtractorConfig, With, With2, With3, WithAsync};
|
||||
|
||||
/// Resource route definition
|
||||
///
|
||||
@ -129,6 +129,34 @@ impl<S: 'static> Route<S> {
|
||||
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// It is possible to use tuples for specifing multiple extractors for one
|
||||
/// handler function.
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate bytes;
|
||||
/// # extern crate actix_web;
|
||||
/// # extern crate futures;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// # use std::collections::HashMap;
|
||||
/// use actix_web::{http, App, Query, Path, Result, Json};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct Info {
|
||||
/// username: String,
|
||||
/// }
|
||||
///
|
||||
/// /// extract path info using serde
|
||||
/// fn index(info: (Path<Info>, Query<HashMap<String, String>>, Json<Info>)) -> Result<String> {
|
||||
/// Ok(format!("Welcome {}!", info.0.username))
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
pub fn with<T, F, R>(&mut self, handler: F) -> ExtractorConfig<S, T>
|
||||
where
|
||||
F: Fn(T) -> R + 'static,
|
||||
@ -140,6 +168,49 @@ impl<S: 'static> Route<S> {
|
||||
cfg
|
||||
}
|
||||
|
||||
/// Set async handler function, use request extractor for parameters.
|
||||
/// Also this method needs to be used if your handler function returns
|
||||
/// `impl Future<>`
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate bytes;
|
||||
/// # extern crate actix_web;
|
||||
/// # extern crate futures;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// use actix_web::{App, Path, Error, http};
|
||||
/// use futures::Future;
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct Info {
|
||||
/// username: String,
|
||||
/// }
|
||||
///
|
||||
/// /// extract path info using serde
|
||||
/// fn index(info: Path<Info>) -> Box<Future<Item=&'static str, Error=Error>> {
|
||||
/// unimplemented!()
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/{username}/index.html", // <- define path parameters
|
||||
/// |r| r.method(http::Method::GET)
|
||||
/// .with_async(index)); // <- use `with` extractor
|
||||
/// }
|
||||
/// ```
|
||||
pub fn with_async<T, F, R, I, E>(&mut self, handler: F) -> ExtractorConfig<S, T>
|
||||
where
|
||||
F: Fn(T) -> R + 'static,
|
||||
R: Future<Item = I, Error = E> + 'static,
|
||||
I: Responder + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
T: FromRequest<S> + 'static,
|
||||
{
|
||||
let cfg = ExtractorConfig::default();
|
||||
self.h(WithAsync::new(handler, Clone::clone(&cfg)));
|
||||
cfg
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Set handler function, use request extractor for both parameters.
|
||||
///
|
||||
/// ```rust
|
||||
@ -189,6 +260,7 @@ impl<S: 'static> Route<S> {
|
||||
(cfg1, cfg2)
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Set handler function, use request extractor for all parameters.
|
||||
pub fn with3<T1, T2, T3, F, R>(
|
||||
&mut self, handler: F,
|
||||
|
@ -76,7 +76,7 @@ impl<S: 'static> Scope<S> {
|
||||
mem::replace(&mut self.filters, Vec::new())
|
||||
}
|
||||
|
||||
/// Add match predicate to scoupe.
|
||||
/// Add match predicate to scope.
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
@ -787,10 +787,10 @@ mod tests {
|
||||
let mut app = App::new()
|
||||
.scope("app", |scope| {
|
||||
scope
|
||||
.route("/path1", Method::GET, |r: HttpRequest<_>| {
|
||||
.route("/path1", Method::GET, |_: HttpRequest<_>| {
|
||||
HttpResponse::Ok()
|
||||
})
|
||||
.route("/path1", Method::DELETE, |r: HttpRequest<_>| {
|
||||
.route("/path1", Method::DELETE, |_: HttpRequest<_>| {
|
||||
HttpResponse::Ok()
|
||||
})
|
||||
})
|
||||
|
147
src/server/h1.rs
147
src/server/h1.rs
@ -67,7 +67,9 @@ where
|
||||
H: HttpHandler + 'static,
|
||||
{
|
||||
pub fn new(
|
||||
settings: Rc<WorkerSettings<H>>, stream: T, addr: Option<SocketAddr>,
|
||||
settings: Rc<WorkerSettings<H>>,
|
||||
stream: T,
|
||||
addr: Option<SocketAddr>,
|
||||
buf: BytesMut,
|
||||
) -> Self {
|
||||
let bytes = settings.get_shared_bytes();
|
||||
@ -149,7 +151,8 @@ where
|
||||
pub fn poll_io(&mut self) {
|
||||
// read io from socket
|
||||
if !self.flags.intersects(Flags::ERROR)
|
||||
&& self.tasks.len() < MAX_PIPELINED_MESSAGES && self.can_read()
|
||||
&& self.tasks.len() < MAX_PIPELINED_MESSAGES
|
||||
&& self.can_read()
|
||||
{
|
||||
if self.read() {
|
||||
// notify all tasks
|
||||
@ -205,8 +208,7 @@ where
|
||||
self.stream.reset();
|
||||
|
||||
if ready {
|
||||
item.flags
|
||||
.insert(EntryFlags::EOF | EntryFlags::FINISHED);
|
||||
item.flags.insert(EntryFlags::EOF | EntryFlags::FINISHED);
|
||||
} else {
|
||||
item.flags.insert(EntryFlags::FINISHED);
|
||||
}
|
||||
@ -347,6 +349,7 @@ where
|
||||
} else {
|
||||
error!("Internal server error: unexpected payload chunk");
|
||||
self.flags.insert(Flags::ERROR);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Some(Message::Eof)) => {
|
||||
@ -355,6 +358,7 @@ where
|
||||
} else {
|
||||
error!("Internal server error: unexpected eof");
|
||||
self.flags.insert(Flags::ERROR);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(None) => break,
|
||||
@ -367,6 +371,7 @@ where
|
||||
};
|
||||
payload.set_error(e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -398,8 +403,12 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use std::net::Shutdown;
|
||||
use std::{cmp, time};
|
||||
|
||||
use bytes::{Buf, Bytes, BytesMut};
|
||||
use http::{Method, Version};
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use super::*;
|
||||
use application::HttpApplication;
|
||||
@ -463,6 +472,101 @@ mod tests {
|
||||
}};
|
||||
}
|
||||
|
||||
struct Buffer {
|
||||
buf: Bytes,
|
||||
err: Option<io::Error>,
|
||||
}
|
||||
|
||||
impl Buffer {
|
||||
fn new(data: &'static str) -> Buffer {
|
||||
Buffer {
|
||||
buf: Bytes::from(data),
|
||||
err: None,
|
||||
}
|
||||
}
|
||||
fn feed_data(&mut self, data: &'static str) {
|
||||
let mut b = BytesMut::from(self.buf.as_ref());
|
||||
b.extend(data.as_bytes());
|
||||
self.buf = b.take().freeze();
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for Buffer {}
|
||||
impl io::Read for Buffer {
|
||||
fn read(&mut self, dst: &mut [u8]) -> Result<usize, io::Error> {
|
||||
if self.buf.is_empty() {
|
||||
if self.err.is_some() {
|
||||
Err(self.err.take().unwrap())
|
||||
} else {
|
||||
Err(io::Error::new(io::ErrorKind::WouldBlock, ""))
|
||||
}
|
||||
} else {
|
||||
let size = cmp::min(self.buf.len(), dst.len());
|
||||
let b = self.buf.split_to(size);
|
||||
dst[..size].copy_from_slice(&b);
|
||||
Ok(size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IoStream for Buffer {
|
||||
fn shutdown(&mut self, _: Shutdown) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn set_nodelay(&mut self, _: bool) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn set_linger(&mut self, _: Option<time::Duration>) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl io::Write for Buffer {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
Ok(buf.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl AsyncWrite for Buffer {
|
||||
fn shutdown(&mut self) -> Poll<(), io::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
fn write_buf<B: Buf>(&mut self, _: &mut B) -> Poll<usize, io::Error> {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_req_parse() {
|
||||
let buf = Buffer::new("GET /test HTTP/1.1\r\n\r\n");
|
||||
let readbuf = BytesMut::new();
|
||||
let settings = Rc::new(WorkerSettings::<HttpApplication>::new(
|
||||
Vec::new(),
|
||||
KeepAlive::Os,
|
||||
));
|
||||
|
||||
let mut h1 = Http1::new(Rc::clone(&settings), buf, None, readbuf);
|
||||
h1.poll_io();
|
||||
h1.parse();
|
||||
assert_eq!(h1.tasks.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_req_parse_err() {
|
||||
let buf = Buffer::new("GET /test HTTP/1\r\n\r\n");
|
||||
let readbuf = BytesMut::new();
|
||||
let settings = Rc::new(WorkerSettings::<HttpApplication>::new(
|
||||
Vec::new(),
|
||||
KeepAlive::Os,
|
||||
));
|
||||
|
||||
let mut h1 = Http1::new(Rc::clone(&settings), buf, None, readbuf);
|
||||
h1.poll_io();
|
||||
h1.parse();
|
||||
assert!(h1.flags.contains(Flags::ERROR));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse() {
|
||||
let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n\r\n");
|
||||
@ -614,10 +718,7 @@ mod tests {
|
||||
assert_eq!(req.version(), Version::HTTP_11);
|
||||
assert_eq!(*req.method(), Method::GET);
|
||||
assert_eq!(req.path(), "/test");
|
||||
assert_eq!(
|
||||
req.headers().get("test").unwrap().as_bytes(),
|
||||
b"value"
|
||||
);
|
||||
assert_eq!(req.headers().get("test").unwrap().as_bytes(), b"value");
|
||||
}
|
||||
Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
|
||||
}
|
||||
@ -918,13 +1019,7 @@ mod tests {
|
||||
.as_ref(),
|
||||
b"line"
|
||||
);
|
||||
assert!(
|
||||
reader
|
||||
.decode(&mut buf, &settings)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.eof()
|
||||
);
|
||||
assert!(reader.decode(&mut buf, &settings).unwrap().unwrap().eof());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -1005,13 +1100,7 @@ mod tests {
|
||||
assert!(reader.decode(&mut buf, &settings).unwrap().is_none());
|
||||
|
||||
buf.extend(b"\r\n");
|
||||
assert!(
|
||||
reader
|
||||
.decode(&mut buf, &settings)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.eof()
|
||||
);
|
||||
assert!(reader.decode(&mut buf, &settings).unwrap().unwrap().eof());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -1029,17 +1118,9 @@ mod tests {
|
||||
assert!(req.chunked().unwrap());
|
||||
|
||||
buf.extend(b"4;test\r\ndata\r\n4\r\nline\r\n0\r\n\r\n"); // test: test\r\n\r\n")
|
||||
let chunk = reader
|
||||
.decode(&mut buf, &settings)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.chunk();
|
||||
let chunk = reader.decode(&mut buf, &settings).unwrap().unwrap().chunk();
|
||||
assert_eq!(chunk, Bytes::from_static(b"data"));
|
||||
let chunk = reader
|
||||
.decode(&mut buf, &settings)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.chunk();
|
||||
let chunk = reader.decode(&mut buf, &settings).unwrap().unwrap().chunk();
|
||||
assert_eq!(chunk, Bytes::from_static(b"line"));
|
||||
let msg = reader.decode(&mut buf, &settings).unwrap().unwrap();
|
||||
assert!(msg.eof());
|
||||
|
@ -343,24 +343,27 @@ impl<H: 'static> Entry<H> {
|
||||
}
|
||||
|
||||
fn poll_payload(&mut self) {
|
||||
if !self.flags.contains(EntryFlags::REOF) {
|
||||
if self.payload.need_read() == PayloadStatus::Read {
|
||||
if let Err(err) = self.recv.release_capacity().release_capacity(32_768) {
|
||||
self.payload.set_error(PayloadError::Http2(err))
|
||||
}
|
||||
} else if let Err(err) = self.recv.release_capacity().release_capacity(0) {
|
||||
self.payload.set_error(PayloadError::Http2(err))
|
||||
}
|
||||
|
||||
while !self.flags.contains(EntryFlags::REOF)
|
||||
&& self.payload.need_read() == PayloadStatus::Read
|
||||
{
|
||||
match self.recv.poll() {
|
||||
Ok(Async::Ready(Some(chunk))) => {
|
||||
let l = chunk.len();
|
||||
self.payload.feed_data(chunk);
|
||||
if let Err(err) = self.recv.release_capacity().release_capacity(l) {
|
||||
self.payload.set_error(PayloadError::Http2(err));
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Async::Ready(None)) => {
|
||||
self.flags.insert(EntryFlags::REOF);
|
||||
self.payload.feed_eof();
|
||||
}
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(err) => {
|
||||
self.payload.set_error(PayloadError::Http2(err));
|
||||
break;
|
||||
}
|
||||
Ok(Async::NotReady) => (),
|
||||
Err(err) => self.payload.set_error(PayloadError::Http2(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -16,7 +16,6 @@ use body::Body;
|
||||
use httpresponse::{HttpResponse, HttpResponseBuilder, HttpResponsePool};
|
||||
|
||||
/// Various server settings
|
||||
#[derive(Clone)]
|
||||
pub struct ServerSettings {
|
||||
addr: Option<net::SocketAddr>,
|
||||
secure: bool,
|
||||
@ -28,6 +27,18 @@ pub struct ServerSettings {
|
||||
unsafe impl Sync for ServerSettings {}
|
||||
unsafe impl Send for ServerSettings {}
|
||||
|
||||
impl Clone for ServerSettings {
|
||||
fn clone(&self) -> Self {
|
||||
ServerSettings {
|
||||
addr: self.addr,
|
||||
secure: self.secure,
|
||||
host: self.host.clone(),
|
||||
cpu_pool: self.cpu_pool.clone(),
|
||||
responses: HttpResponsePool::pool(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct InnerCpuPool {
|
||||
cpu_pool: UnsafeCell<Option<CpuPool>>,
|
||||
}
|
||||
|
15
src/test.rs
15
src/test.rs
@ -355,12 +355,7 @@ impl<S: 'static> TestApp<S> {
|
||||
|
||||
/// Register handler for "/"
|
||||
pub fn handler<H: Handler<S>>(&mut self, handler: H) {
|
||||
self.app = Some(
|
||||
self.app
|
||||
.take()
|
||||
.unwrap()
|
||||
.resource("/", |r| r.h(handler)),
|
||||
);
|
||||
self.app = Some(self.app.take().unwrap().resource("/", |r| r.h(handler)));
|
||||
}
|
||||
|
||||
/// Register middleware
|
||||
@ -562,8 +557,8 @@ impl<S: 'static> TestRequest<S> {
|
||||
cookies,
|
||||
payload,
|
||||
} = self;
|
||||
let req = HttpRequest::new(method, uri, version, headers, payload);
|
||||
req.as_mut().cookies = cookies;
|
||||
let mut req = HttpRequest::new(method, uri, version, headers, payload);
|
||||
req.set_cookies(cookies);
|
||||
req.as_mut().params = params;
|
||||
let (router, _) = Router::new::<S>("/", ServerSettings::default(), Vec::new());
|
||||
req.with_state(Rc::new(state), router)
|
||||
@ -583,8 +578,8 @@ impl<S: 'static> TestRequest<S> {
|
||||
payload,
|
||||
} = self;
|
||||
|
||||
let req = HttpRequest::new(method, uri, version, headers, payload);
|
||||
req.as_mut().cookies = cookies;
|
||||
let mut req = HttpRequest::new(method, uri, version, headers, payload);
|
||||
req.set_cookies(cookies);
|
||||
req.as_mut().params = params;
|
||||
req.with_state(Rc::new(state), router)
|
||||
}
|
||||
|
195
src/with.rs
195
src/with.rs
@ -9,6 +9,62 @@ use handler::{AsyncResult, AsyncResultItem, FromRequest, Handler, Responder};
|
||||
use httprequest::HttpRequest;
|
||||
use httpresponse::HttpResponse;
|
||||
|
||||
/// Extractor configuration
|
||||
///
|
||||
/// `Route::with()` and `Route::with_async()` returns instance
|
||||
/// of the `ExtractorConfig` type. It could be used for extractor configuration.
|
||||
///
|
||||
/// In this example `Form<FormData>` configured.
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// use actix_web::{App, Form, Result, http};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct FormData {
|
||||
/// username: String,
|
||||
/// }
|
||||
///
|
||||
/// fn index(form: Form<FormData>) -> Result<String> {
|
||||
/// Ok(format!("Welcome {}!", form.username))
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/index.html", |r| {
|
||||
/// r.method(http::Method::GET)
|
||||
/// .with(index)
|
||||
/// .limit(4096);} // <- change form extractor configuration
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Same could be donce with multiple extractors
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_web;
|
||||
/// #[macro_use] extern crate serde_derive;
|
||||
/// use actix_web::{App, Form, Path, Result, http};
|
||||
///
|
||||
/// #[derive(Deserialize)]
|
||||
/// struct FormData {
|
||||
/// username: String,
|
||||
/// }
|
||||
///
|
||||
/// fn index(data: (Path<(String,)>, Form<FormData>)) -> Result<String> {
|
||||
/// Ok(format!("Welcome {}!", data.1.username))
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let app = App::new().resource(
|
||||
/// "/index.html", |r| {
|
||||
/// r.method(http::Method::GET)
|
||||
/// .with(index)
|
||||
/// .1.limit(4096);} // <- change form extractor configuration
|
||||
/// );
|
||||
/// }
|
||||
/// ```
|
||||
pub struct ExtractorConfig<S: 'static, T: FromRequest<S>> {
|
||||
cfg: Rc<UnsafeCell<T::Config>>,
|
||||
}
|
||||
@ -167,6 +223,145 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WithAsync<T, S, F, R, I, E>
|
||||
where
|
||||
F: Fn(T) -> R,
|
||||
R: Future<Item = I, Error = E>,
|
||||
I: Responder,
|
||||
E: Into<E>,
|
||||
T: FromRequest<S>,
|
||||
S: 'static,
|
||||
{
|
||||
hnd: Rc<UnsafeCell<F>>,
|
||||
cfg: ExtractorConfig<S, T>,
|
||||
_s: PhantomData<S>,
|
||||
}
|
||||
|
||||
impl<T, S, F, R, I, E> WithAsync<T, S, F, R, I, E>
|
||||
where
|
||||
F: Fn(T) -> R,
|
||||
R: Future<Item = I, Error = E>,
|
||||
I: Responder,
|
||||
E: Into<Error>,
|
||||
T: FromRequest<S>,
|
||||
S: 'static,
|
||||
{
|
||||
pub fn new(f: F, cfg: ExtractorConfig<S, T>) -> Self {
|
||||
WithAsync {
|
||||
cfg,
|
||||
hnd: Rc::new(UnsafeCell::new(f)),
|
||||
_s: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, R, I, E> Handler<S> for WithAsync<T, S, F, R, I, E>
|
||||
where
|
||||
F: Fn(T) -> R + 'static,
|
||||
R: Future<Item = I, Error = E> + 'static,
|
||||
I: Responder + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
T: FromRequest<S> + 'static,
|
||||
S: 'static,
|
||||
{
|
||||
type Result = AsyncResult<HttpResponse>;
|
||||
|
||||
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
|
||||
let mut fut = WithAsyncHandlerFut {
|
||||
req,
|
||||
started: false,
|
||||
hnd: Rc::clone(&self.hnd),
|
||||
cfg: self.cfg.clone(),
|
||||
fut1: None,
|
||||
fut2: None,
|
||||
fut3: None,
|
||||
};
|
||||
|
||||
match fut.poll() {
|
||||
Ok(Async::Ready(resp)) => AsyncResult::ok(resp),
|
||||
Ok(Async::NotReady) => AsyncResult::async(Box::new(fut)),
|
||||
Err(e) => AsyncResult::err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct WithAsyncHandlerFut<T, S, F, R, I, E>
|
||||
where
|
||||
F: Fn(T) -> R,
|
||||
R: Future<Item = I, Error = E> + 'static,
|
||||
I: Responder + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
T: FromRequest<S> + 'static,
|
||||
S: 'static,
|
||||
{
|
||||
started: bool,
|
||||
hnd: Rc<UnsafeCell<F>>,
|
||||
cfg: ExtractorConfig<S, T>,
|
||||
req: HttpRequest<S>,
|
||||
fut1: Option<Box<Future<Item = T, Error = Error>>>,
|
||||
fut2: Option<R>,
|
||||
fut3: Option<Box<Future<Item = HttpResponse, Error = Error>>>,
|
||||
}
|
||||
|
||||
impl<T, S, F, R, I, E> Future for WithAsyncHandlerFut<T, S, F, R, I, E>
|
||||
where
|
||||
F: Fn(T) -> R,
|
||||
R: Future<Item = I, Error = E> + 'static,
|
||||
I: Responder + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
T: FromRequest<S> + 'static,
|
||||
S: 'static,
|
||||
{
|
||||
type Item = HttpResponse;
|
||||
type Error = Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut3 {
|
||||
return fut.poll();
|
||||
}
|
||||
|
||||
if self.fut2.is_some() {
|
||||
return match self.fut2.as_mut().unwrap().poll() {
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Ok(Async::Ready(r)) => match r.respond_to(&self.req) {
|
||||
Ok(r) => match r.into().into() {
|
||||
AsyncResultItem::Err(err) => Err(err),
|
||||
AsyncResultItem::Ok(resp) => Ok(Async::Ready(resp)),
|
||||
AsyncResultItem::Future(fut) => {
|
||||
self.fut3 = Some(fut);
|
||||
self.poll()
|
||||
}
|
||||
},
|
||||
Err(e) => Err(e.into()),
|
||||
},
|
||||
Err(e) => Err(e.into()),
|
||||
};
|
||||
}
|
||||
|
||||
let item = if !self.started {
|
||||
self.started = true;
|
||||
let reply = T::from_request(&self.req, self.cfg.as_ref()).into();
|
||||
match reply.into() {
|
||||
AsyncResultItem::Err(err) => return Err(err),
|
||||
AsyncResultItem::Ok(msg) => msg,
|
||||
AsyncResultItem::Future(fut) => {
|
||||
self.fut1 = Some(fut);
|
||||
return self.poll();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match self.fut1.as_mut().unwrap().poll()? {
|
||||
Async::Ready(item) => item,
|
||||
Async::NotReady => return Ok(Async::NotReady),
|
||||
}
|
||||
};
|
||||
|
||||
let hnd: &mut F = unsafe { &mut *self.hnd.get() };
|
||||
self.fut2 = Some((*hnd)(item));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct With2<T1, T2, S, F, R>
|
||||
where
|
||||
F: Fn(T1, T2) -> R,
|
||||
|
@ -518,24 +518,22 @@ impl ClientWriter {
|
||||
fn as_mut(&mut self) -> &mut Inner {
|
||||
unsafe { &mut *self.inner.get() }
|
||||
}
|
||||
}
|
||||
|
||||
impl WsWriter for ClientWriter {
|
||||
/// Send text frame
|
||||
#[inline]
|
||||
fn text<T: Into<Binary>>(&mut self, text: T) {
|
||||
pub fn text<T: Into<Binary>>(&mut self, text: T) {
|
||||
self.write(Frame::message(text.into(), OpCode::Text, true, true));
|
||||
}
|
||||
|
||||
/// Send binary frame
|
||||
#[inline]
|
||||
fn binary<B: Into<Binary>>(&mut self, data: B) {
|
||||
pub fn binary<B: Into<Binary>>(&mut self, data: B) {
|
||||
self.write(Frame::message(data, OpCode::Binary, true, true));
|
||||
}
|
||||
|
||||
/// Send ping frame
|
||||
#[inline]
|
||||
fn ping(&mut self, message: &str) {
|
||||
pub fn ping(&mut self, message: &str) {
|
||||
self.write(Frame::message(
|
||||
Vec::from(message),
|
||||
OpCode::Ping,
|
||||
@ -546,7 +544,7 @@ impl WsWriter for ClientWriter {
|
||||
|
||||
/// Send pong frame
|
||||
#[inline]
|
||||
fn pong(&mut self, message: &str) {
|
||||
pub fn pong(&mut self, message: &str) {
|
||||
self.write(Frame::message(
|
||||
Vec::from(message),
|
||||
OpCode::Pong,
|
||||
@ -557,7 +555,39 @@ impl WsWriter for ClientWriter {
|
||||
|
||||
/// Send close frame
|
||||
#[inline]
|
||||
fn close(&mut self, reason: Option<CloseReason>) {
|
||||
pub fn close(&mut self, reason: Option<CloseReason>) {
|
||||
self.write(Frame::close(reason, true));
|
||||
}
|
||||
}
|
||||
|
||||
impl WsWriter for ClientWriter {
|
||||
/// Send text frame
|
||||
#[inline]
|
||||
fn send_text<T: Into<Binary>>(&mut self, text: T) {
|
||||
self.text(text)
|
||||
}
|
||||
|
||||
/// Send binary frame
|
||||
#[inline]
|
||||
fn send_binary<B: Into<Binary>>(&mut self, data: B) {
|
||||
self.binary(data)
|
||||
}
|
||||
|
||||
/// Send ping frame
|
||||
#[inline]
|
||||
fn send_ping(&mut self, message: &str) {
|
||||
self.ping(message)
|
||||
}
|
||||
|
||||
/// Send pong frame
|
||||
#[inline]
|
||||
fn send_pong(&mut self, message: &str) {
|
||||
self.pong(message)
|
||||
}
|
||||
|
||||
/// Send close frame
|
||||
#[inline]
|
||||
fn send_close(&mut self, reason: Option<CloseReason>) {
|
||||
self.close(reason);
|
||||
}
|
||||
}
|
||||
|
@ -149,6 +149,46 @@ where
|
||||
Drain::new(rx)
|
||||
}
|
||||
|
||||
/// Send text frame
|
||||
#[inline]
|
||||
pub fn text<T: Into<Binary>>(&mut self, text: T) {
|
||||
self.write(Frame::message(text.into(), OpCode::Text, true, false));
|
||||
}
|
||||
|
||||
/// Send binary frame
|
||||
#[inline]
|
||||
pub fn binary<B: Into<Binary>>(&mut self, data: B) {
|
||||
self.write(Frame::message(data, OpCode::Binary, true, false));
|
||||
}
|
||||
|
||||
/// Send ping frame
|
||||
#[inline]
|
||||
pub fn ping(&mut self, message: &str) {
|
||||
self.write(Frame::message(
|
||||
Vec::from(message),
|
||||
OpCode::Ping,
|
||||
true,
|
||||
false,
|
||||
));
|
||||
}
|
||||
|
||||
/// Send pong frame
|
||||
#[inline]
|
||||
pub fn pong(&mut self, message: &str) {
|
||||
self.write(Frame::message(
|
||||
Vec::from(message),
|
||||
OpCode::Pong,
|
||||
true,
|
||||
false,
|
||||
));
|
||||
}
|
||||
|
||||
/// Send close frame
|
||||
#[inline]
|
||||
pub fn close(&mut self, reason: Option<CloseReason>) {
|
||||
self.write(Frame::close(reason, false));
|
||||
}
|
||||
|
||||
/// Check if connection still open
|
||||
#[inline]
|
||||
pub fn connected(&self) -> bool {
|
||||
@ -181,42 +221,32 @@ where
|
||||
{
|
||||
/// Send text frame
|
||||
#[inline]
|
||||
fn text<T: Into<Binary>>(&mut self, text: T) {
|
||||
self.write(Frame::message(text.into(), OpCode::Text, true, false));
|
||||
fn send_text<T: Into<Binary>>(&mut self, text: T) {
|
||||
self.text(text)
|
||||
}
|
||||
|
||||
/// Send binary frame
|
||||
#[inline]
|
||||
fn binary<B: Into<Binary>>(&mut self, data: B) {
|
||||
self.write(Frame::message(data, OpCode::Binary, true, false));
|
||||
fn send_binary<B: Into<Binary>>(&mut self, data: B) {
|
||||
self.binary(data)
|
||||
}
|
||||
|
||||
/// Send ping frame
|
||||
#[inline]
|
||||
fn ping(&mut self, message: &str) {
|
||||
self.write(Frame::message(
|
||||
Vec::from(message),
|
||||
OpCode::Ping,
|
||||
true,
|
||||
false,
|
||||
));
|
||||
fn send_ping(&mut self, message: &str) {
|
||||
self.ping(message)
|
||||
}
|
||||
|
||||
/// Send pong frame
|
||||
#[inline]
|
||||
fn pong(&mut self, message: &str) {
|
||||
self.write(Frame::message(
|
||||
Vec::from(message),
|
||||
OpCode::Pong,
|
||||
true,
|
||||
false,
|
||||
));
|
||||
fn send_pong(&mut self, message: &str) {
|
||||
self.pong(message)
|
||||
}
|
||||
|
||||
/// Send close frame
|
||||
#[inline]
|
||||
fn close(&mut self, reason: Option<CloseReason>) {
|
||||
self.write(Frame::close(reason, false));
|
||||
fn send_close(&mut self, reason: Option<CloseReason>) {
|
||||
self.close(reason)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -343,15 +343,15 @@ where
|
||||
/// Common writing methods for a websocket.
|
||||
pub trait WsWriter {
|
||||
/// Send a text
|
||||
fn text<T: Into<Binary>>(&mut self, text: T);
|
||||
fn send_text<T: Into<Binary>>(&mut self, text: T);
|
||||
/// Send a binary
|
||||
fn binary<B: Into<Binary>>(&mut self, data: B);
|
||||
fn send_binary<B: Into<Binary>>(&mut self, data: B);
|
||||
/// Send a ping message
|
||||
fn ping(&mut self, message: &str);
|
||||
fn send_ping(&mut self, message: &str);
|
||||
/// Send a pong message
|
||||
fn pong(&mut self, message: &str);
|
||||
fn send_pong(&mut self, message: &str);
|
||||
/// Close the connection
|
||||
fn close(&mut self, reason: Option<CloseReason>);
|
||||
fn send_close(&mut self, reason: Option<CloseReason>);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -9,6 +9,7 @@ extern crate tokio_core;
|
||||
extern crate serde_derive;
|
||||
extern crate serde_json;
|
||||
|
||||
use std::io;
|
||||
use std::time::Duration;
|
||||
|
||||
use actix::*;
|
||||
@ -377,6 +378,83 @@ fn test_path_and_query_extractor2_async4() {
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[cfg(actix_impl_trait)]
|
||||
fn test_impl_trait(
|
||||
data: (Json<Value>, Path<PParam>, Query<PParam>),
|
||||
) -> impl Future<Item = String, Error = io::Error> {
|
||||
Timeout::new(Duration::from_millis(10), &Arbiter::handle())
|
||||
.unwrap()
|
||||
.and_then(move |_| {
|
||||
Ok(format!(
|
||||
"Welcome {} - {}!",
|
||||
data.1.username,
|
||||
(data.0).0
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(actix_impl_trait)]
|
||||
fn test_impl_trait_err(
|
||||
_data: (Json<Value>, Path<PParam>, Query<PParam>),
|
||||
) -> impl Future<Item = String, Error = io::Error> {
|
||||
Timeout::new(Duration::from_millis(10), &Arbiter::handle())
|
||||
.unwrap()
|
||||
.and_then(move |_| Err(io::Error::new(io::ErrorKind::Other, "other")))
|
||||
}
|
||||
|
||||
#[cfg(actix_impl_trait)]
|
||||
#[test]
|
||||
fn test_path_and_query_extractor2_async4_impl_trait() {
|
||||
let mut srv = test::TestServer::new(|app| {
|
||||
app.resource("/{username}/index.html", |r| {
|
||||
r.route().with_async(test_impl_trait)
|
||||
});
|
||||
});
|
||||
|
||||
// client request
|
||||
let request = srv.post()
|
||||
.uri(srv.url("/test1/index.html?username=test2"))
|
||||
.header("content-type", "application/json")
|
||||
.body("{\"test\": 1}")
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert!(response.status().is_success());
|
||||
|
||||
// read response
|
||||
let bytes = srv.execute(response.body()).unwrap();
|
||||
assert_eq!(
|
||||
bytes,
|
||||
Bytes::from_static(b"Welcome test1 - {\"test\":1}!")
|
||||
);
|
||||
|
||||
// client request
|
||||
let request = srv.get()
|
||||
.uri(srv.url("/test1/index.html"))
|
||||
.finish()
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[cfg(actix_impl_trait)]
|
||||
#[test]
|
||||
fn test_path_and_query_extractor2_async4_impl_trait_err() {
|
||||
let mut srv = test::TestServer::new(|app| {
|
||||
app.resource("/{username}/index.html", |r| {
|
||||
r.route().with_async(test_impl_trait_err)
|
||||
});
|
||||
});
|
||||
|
||||
// client request
|
||||
let request = srv.post()
|
||||
.uri(srv.url("/test1/index.html?username=test2"))
|
||||
.header("content-type", "application/json")
|
||||
.body("{\"test\": 1}")
|
||||
.unwrap();
|
||||
let response = srv.execute(request.send()).unwrap();
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_ascii_route() {
|
||||
let mut srv = test::TestServer::new(|app| {
|
||||
|
@ -809,7 +809,7 @@ fn test_h2() {
|
||||
})
|
||||
});
|
||||
let _res = core.run(tcp);
|
||||
// assert_eq!(res.unwrap(), Bytes::from_static(STR.as_ref()));
|
||||
// assert_eq!(_res.unwrap(), Bytes::from_static(STR.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
Reference in New Issue
Block a user