1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-30 18:44:35 +01:00

convert to 2018 edition

This commit is contained in:
Nikolay Kim 2018-12-06 14:32:52 -08:00
parent c0f8bc9e90
commit e9121025b7
40 changed files with 310 additions and 294 deletions

View File

@ -13,6 +13,7 @@ categories = ["network-programming", "asynchronous",
"web-programming::websocket"] "web-programming::websocket"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["session"] features = ["session"]

View File

@ -34,7 +34,9 @@ fn main() {
res.header("x-head", HeaderValue::from_static("dummy value!")); res.header("x-head", HeaderValue::from_static("dummy value!"));
Ok(res.body(bytes)) Ok(res.body(bytes))
}) })
}).map(|_| ()) })
}).unwrap() .map(|_| ())
})
.unwrap()
.run(); .run();
} }

View File

@ -37,6 +37,7 @@ fn main() {
.server_hostname("localhost") .server_hostname("localhost")
.finish(|_req: Request| handle_request(_req)) .finish(|_req: Request| handle_request(_req))
.map(|_| ()) .map(|_| ())
}).unwrap() })
.unwrap()
.run(); .run();
} }

View File

@ -29,6 +29,7 @@ fn main() {
.map_err(|_| ()) .map_err(|_| ())
.map(|_| ()) .map(|_| ())
}) })
}).unwrap() })
.unwrap()
.run(); .run();
} }

View File

@ -29,7 +29,9 @@ fn main() {
let mut res = Response::Ok(); let mut res = Response::Ok();
res.header("x-head", HeaderValue::from_static("dummy value!")); res.header("x-head", HeaderValue::from_static("dummy value!"));
future::ok::<_, ()>(res.body("Hello world!")) future::ok::<_, ()>(res.body("Hello world!"))
}).map(|_| ()) })
}).unwrap() .map(|_| ())
})
.unwrap()
.run(); .run();
} }

View File

@ -4,7 +4,7 @@ use std::{fmt, mem};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::{Async, Poll, Stream}; use futures::{Async, Poll, Stream};
use error::{Error, PayloadError}; use crate::error::{Error, PayloadError};
/// Type represent streaming payload /// Type represent streaming payload
pub type PayloadStream = Box<dyn Stream<Item = Bytes, Error = PayloadError>>; pub type PayloadStream = Box<dyn Stream<Item = Bytes, Error = PayloadError>>;

View File

@ -143,7 +143,8 @@ impl Connector {
self.resolver self.resolver
.map_err(ConnectorError::from) .map_err(ConnectorError::from)
.and_then(TcpConnector::default().from_err()), .and_then(TcpConnector::default().from_err()),
).map_err(|e| match e { )
.map_err(|e| match e {
TimeoutError::Service(e) => e, TimeoutError::Service(e) => e,
TimeoutError::Timeout => ConnectorError::Timeout, TimeoutError::Timeout => ConnectorError::Timeout,
}); });
@ -170,7 +171,8 @@ impl Connector {
OpensslConnector::service(self.connector) OpensslConnector::service(self.connector)
.map_err(ConnectorError::SslError), .map_err(ConnectorError::SslError),
), ),
).map_err(|e| match e { )
.map_err(|e| match e {
TimeoutError::Service(e) => e, TimeoutError::Service(e) => e,
TimeoutError::Timeout => ConnectorError::Timeout, TimeoutError::Timeout => ConnectorError::Timeout,
}); });
@ -180,7 +182,8 @@ impl Connector {
self.resolver self.resolver
.map_err(ConnectorError::from) .map_err(ConnectorError::from)
.and_then(TcpConnector::default().from_err()), .and_then(TcpConnector::default().from_err()),
).map_err(|e| match e { )
.map_err(|e| match e {
TimeoutError::Service(e) => e, TimeoutError::Service(e) => e,
TimeoutError::Timeout => ConnectorError::Timeout, TimeoutError::Timeout => ConnectorError::Timeout,
}); });
@ -271,16 +274,8 @@ mod connect_impl {
where where
Io1: AsyncRead + AsyncWrite + 'static, Io1: AsyncRead + AsyncWrite + 'static,
Io2: AsyncRead + AsyncWrite + 'static, Io2: AsyncRead + AsyncWrite + 'static,
T1: Service< T1: Service<Connect, Response = (Connect, Io1), Error = ConnectorError>,
Connect, T2: Service<Connect, Response = (Connect, Io2), Error = ConnectorError>,
Response = (Connect, Io1),
Error = ConnectorError,
>,
T2: Service<
Connect,
Response = (Connect, Io2),
Error = ConnectorError,
>,
{ {
pub(crate) tcp_pool: ConnectionPool<T1, Io1>, pub(crate) tcp_pool: ConnectionPool<T1, Io1>,
pub(crate) ssl_pool: ConnectionPool<T2, Io2>, pub(crate) ssl_pool: ConnectionPool<T2, Io2>,

View File

@ -1,23 +1,18 @@
use std::io; use std::io;
use failure::Fail;
use trust_dns_resolver::error::ResolveError; use trust_dns_resolver::error::ResolveError;
#[cfg(feature = "ssl")] #[cfg(feature = "ssl")]
use openssl::ssl::Error as SslError; use openssl::ssl::Error as SslError;
#[cfg(all( #[cfg(all(feature = "tls", not(any(feature = "ssl", feature = "rust-tls"))))]
feature = "tls",
not(any(feature = "ssl", feature = "rust-tls"))
))]
use native_tls::Error as SslError; use native_tls::Error as SslError;
#[cfg(all( #[cfg(all(feature = "rust-tls", not(any(feature = "tls", feature = "ssl"))))]
feature = "rust-tls",
not(any(feature = "tls", feature = "ssl"))
))]
use std::io::Error as SslError; use std::io::Error as SslError;
use error::{Error, ParseError}; use crate::error::{Error, ParseError};
/// A set of errors that can occur while connecting to an HTTP host /// A set of errors that can occur while connecting to an HTTP host
#[derive(Fail, Debug)] #[derive(Fail, Debug)]

View File

@ -10,10 +10,10 @@ use tokio_io::{AsyncRead, AsyncWrite};
use super::error::{ConnectorError, SendRequestError}; use super::error::{ConnectorError, SendRequestError};
use super::response::ClientResponse; use super::response::ClientResponse;
use super::{Connect, Connection}; use super::{Connect, Connection};
use body::{BodyLength, MessageBody, PayloadStream}; use crate::body::{BodyLength, MessageBody, PayloadStream};
use error::PayloadError; use crate::error::PayloadError;
use h1; use crate::h1;
use message::RequestHead; use crate::message::RequestHead;
pub(crate) fn send_request<T, I, B>( pub(crate) fn send_request<T, I, B>(
head: RequestHead, head: RequestHead,
@ -174,14 +174,16 @@ impl<Io: Connection> Stream for Payload<Io> {
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match self.framed.as_mut().unwrap().poll()? { match self.framed.as_mut().unwrap().poll()? {
Async::NotReady => Ok(Async::NotReady), Async::NotReady => Ok(Async::NotReady),
Async::Ready(Some(chunk)) => if let Some(chunk) = chunk { Async::Ready(Some(chunk)) => {
Ok(Async::Ready(Some(chunk))) if let Some(chunk) = chunk {
} else { Ok(Async::Ready(Some(chunk)))
let framed = self.framed.take().unwrap(); } else {
let force_close = framed.get_codec().keepalive(); let framed = self.framed.take().unwrap();
release_connection(framed, force_close); let force_close = framed.get_codec().keepalive();
Ok(Async::Ready(None)) release_connection(framed, force_close);
}, Ok(Async::Ready(None))
}
}
Async::Ready(None) => Ok(Async::Ready(None)), Async::Ready(None) => Ok(Async::Ready(None)),
} }
} }

View File

@ -8,14 +8,14 @@ use cookie::{Cookie, CookieJar};
use futures::{Future, Stream}; use futures::{Future, Stream};
use percent_encoding::{percent_encode, USERINFO_ENCODE_SET}; use percent_encoding::{percent_encode, USERINFO_ENCODE_SET};
use body::{BodyStream, MessageBody}; use crate::body::{BodyStream, MessageBody};
use error::Error; use crate::error::Error;
use header::{self, Header, IntoHeaderValue}; use crate::header::{self, Header, IntoHeaderValue};
use http::{ use crate::http::{
uri, Error as HttpError, HeaderMap, HeaderName, HeaderValue, HttpTryFrom, Method, uri, Error as HttpError, HeaderMap, HeaderName, HeaderValue, HttpTryFrom, Method,
Uri, Version, Uri, Version,
}; };
use message::{ConnectionType, Head, RequestHead}; use crate::message::{ConnectionType, Head, RequestHead};
use super::response::ClientResponse; use super::response::ClientResponse;
use super::{pipeline, Connect, Connection, ConnectorError, SendRequestError}; use super::{pipeline, Connect, Connection, ConnectorError, SendRequestError};
@ -355,14 +355,16 @@ impl ClientRequestBuilder {
{ {
if let Some(parts) = parts(&mut self.head, &self.err) { if let Some(parts) = parts(&mut self.head, &self.err) {
match HeaderName::try_from(key) { match HeaderName::try_from(key) {
Ok(key) => if !parts.headers.contains_key(&key) { Ok(key) => {
match value.try_into() { if !parts.headers.contains_key(&key) {
Ok(value) => { match value.try_into() {
parts.headers.insert(key, value); Ok(value) => {
parts.headers.insert(key, value);
}
Err(e) => self.err = Some(e.into()),
} }
Err(e) => self.err = Some(e.into()),
} }
}, }
Err(e) => self.err = Some(e.into()), Err(e) => self.err = Some(e.into()),
}; };
} }

View File

@ -5,10 +5,10 @@ use bytes::Bytes;
use futures::{Async, Poll, Stream}; use futures::{Async, Poll, Stream};
use http::{HeaderMap, StatusCode, Version}; use http::{HeaderMap, StatusCode, Version};
use body::PayloadStream; use crate::body::PayloadStream;
use error::PayloadError; use crate::error::PayloadError;
use httpmessage::HttpMessage; use crate::httpmessage::HttpMessage;
use message::{Head, ResponseHead}; use crate::message::{Head, ResponseHead};
use super::pipeline::Payload; use super::pipeline::Payload;

View File

@ -6,6 +6,7 @@ use std::{fmt, net};
use bytes::BytesMut; use bytes::BytesMut;
use futures::{future, Future}; use futures::{future, Future};
use log::error;
use time; use time;
use tokio_current_thread::spawn; use tokio_current_thread::spawn;
use tokio_timer::{sleep, Delay}; use tokio_timer::{sleep, Delay};
@ -268,9 +269,11 @@ impl ServiceConfigBuilder {
pub fn server_address<S: net::ToSocketAddrs>(mut self, addr: S) -> Self { pub fn server_address<S: net::ToSocketAddrs>(mut self, addr: S) -> Self {
match addr.to_socket_addrs() { match addr.to_socket_addrs() {
Err(err) => error!("Can not convert to SocketAddr: {}", err), Err(err) => error!("Can not convert to SocketAddr: {}", err),
Ok(mut addrs) => if let Some(addr) = addrs.next() { Ok(mut addrs) => {
self.addr = addr; if let Some(addr) = addrs.next() {
}, self.addr = addr;
}
}
} }
self self
} }

View File

@ -20,8 +20,8 @@ use tokio_timer::Error as TimerError;
// re-exports // re-exports
pub use cookie::ParseError as CookieParseError; pub use cookie::ParseError as CookieParseError;
use body::Body; use crate::body::Body;
use response::{Response, ResponseParts}; use crate::response::{Response, ResponseParts};
/// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html) /// A specialized [`Result`](https://doc.rust-lang.org/std/result/enum.Result.html)
/// for actix web operations /// for actix web operations
@ -186,7 +186,8 @@ impl<T: ResponseError> From<T> for Error {
/// Compatibility for `failure::Error` /// Compatibility for `failure::Error`
impl<T> ResponseError for failure::Compat<T> where impl<T> ResponseError for failure::Compat<T> where
T: fmt::Display + fmt::Debug + Sync + Send + 'static T: fmt::Display + fmt::Debug + Sync + Send + 'static
{} {
}
impl From<failure::Error> for Error { impl From<failure::Error> for Error {
fn from(err: failure::Error) -> Error { fn from(err: failure::Error) -> Error {

View File

@ -1,22 +1,23 @@
#![allow(unused_imports, unused_variables, dead_code)] #![allow(unused_imports, unused_variables, dead_code)]
use std::io::{self, Write}; use std::io::{self, Write};
use bitflags::bitflags;
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use http::header::{
HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, UPGRADE,
};
use http::{Method, Version};
use tokio_codec::{Decoder, Encoder}; use tokio_codec::{Decoder, Encoder};
use super::decoder::{PayloadDecoder, PayloadItem, PayloadType}; use super::decoder::{PayloadDecoder, PayloadItem, PayloadType};
use super::{decoder, encoder}; use super::{decoder, encoder};
use super::{Message, MessageType}; use super::{Message, MessageType};
use body::BodyLength; use crate::body::BodyLength;
use client::ClientResponse; use crate::client::ClientResponse;
use config::ServiceConfig; use crate::config::ServiceConfig;
use error::{ParseError, PayloadError}; use crate::error::{ParseError, PayloadError};
use helpers; use crate::helpers;
use http::header::{ use crate::message::{ConnectionType, Head, MessagePool, RequestHead};
HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, UPGRADE,
};
use http::{Method, Version};
use message::{ConnectionType, Head, MessagePool, RequestHead};
bitflags! { bitflags! {
struct Flags: u8 { struct Flags: u8 {

View File

@ -2,21 +2,22 @@
use std::fmt; use std::fmt;
use std::io::{self, Write}; use std::io::{self, Write};
use bitflags::bitflags;
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING};
use http::{Method, StatusCode, Version};
use tokio_codec::{Decoder, Encoder}; use tokio_codec::{Decoder, Encoder};
use super::decoder::{PayloadDecoder, PayloadItem, PayloadType}; use super::decoder::{PayloadDecoder, PayloadItem, PayloadType};
use super::{decoder, encoder}; use super::{decoder, encoder};
use super::{Message, MessageType}; use super::{Message, MessageType};
use body::BodyLength; use crate::body::BodyLength;
use config::ServiceConfig; use crate::config::ServiceConfig;
use error::ParseError; use crate::error::ParseError;
use helpers; use crate::helpers;
use http::header::{HeaderValue, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING}; use crate::message::{ConnectionType, Head, ResponseHead};
use http::{Method, StatusCode, Version}; use crate::request::Request;
use message::{ConnectionType, Head, ResponseHead}; use crate::response::Response;
use request::Request;
use response::Response;
bitflags! { bitflags! {
struct Flags: u8 { struct Flags: u8 {

View File

@ -3,15 +3,16 @@ use std::{io, mem};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use futures::{Async, Poll}; use futures::{Async, Poll};
use httparse;
use tokio_codec::Decoder;
use client::ClientResponse;
use error::ParseError;
use http::header::{HeaderName, HeaderValue}; use http::header::{HeaderName, HeaderValue};
use http::{header, HeaderMap, HttpTryFrom, Method, StatusCode, Uri, Version}; use http::{header, HeaderMap, HttpTryFrom, Method, StatusCode, Uri, Version};
use message::ConnectionType; use httparse;
use request::Request; use log::{debug, error, trace};
use tokio_codec::Decoder;
use crate::client::ClientResponse;
use crate::error::ParseError;
use crate::message::ConnectionType;
use crate::request::Request;
const MAX_BUFFER_SIZE: usize = 131_072; const MAX_BUFFER_SIZE: usize = 131_072;
const MAX_HEADERS: usize = 96; const MAX_HEADERS: usize = 96;
@ -825,13 +826,13 @@ mod tests {
let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n"); let mut buf = BytesMut::from("GET /test HTTP/1.1\r\n");
let mut reader = MessageDecoder::<Request>::default(); let mut reader = MessageDecoder::<Request>::default();
assert!{ reader.decode(&mut buf).unwrap().is_none() } assert! { reader.decode(&mut buf).unwrap().is_none() }
buf.extend(b"t"); buf.extend(b"t");
assert!{ reader.decode(&mut buf).unwrap().is_none() } assert! { reader.decode(&mut buf).unwrap().is_none() }
buf.extend(b"es"); buf.extend(b"es");
assert!{ reader.decode(&mut buf).unwrap().is_none() } assert! { reader.decode(&mut buf).unwrap().is_none() }
buf.extend(b"t: value\r\n\r\n"); buf.extend(b"t: value\r\n\r\n");
let (req, _) = reader.decode(&mut buf).unwrap().unwrap(); let (req, _) = reader.decode(&mut buf).unwrap().unwrap();

View File

@ -5,19 +5,19 @@ use std::time::Instant;
use actix_net::codec::Framed; use actix_net::codec::Framed;
use actix_net::service::Service; use actix_net::service::Service;
use bitflags::bitflags;
use futures::{Async, Future, Poll, Sink, Stream}; use futures::{try_ready, Async, Future, Poll, Sink, Stream};
use log::{debug, error, trace};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use tokio_timer::Delay; use tokio_timer::Delay;
use error::{ParseError, PayloadError}; use crate::body::{Body, BodyLength, MessageBody, ResponseBody};
use payload::{Payload, PayloadSender, PayloadStatus, PayloadWriter}; use crate::config::ServiceConfig;
use crate::error::DispatchError;
use body::{Body, BodyLength, MessageBody, ResponseBody}; use crate::error::{ParseError, PayloadError};
use config::ServiceConfig; use crate::payload::{Payload, PayloadSender, PayloadStatus, PayloadWriter};
use error::DispatchError; use crate::request::Request;
use request::Request; use crate::response::Response;
use response::Response;
use super::codec::Codec; use super::codec::Codec;
use super::{H1ServiceResult, Message, MessageType}; use super::{H1ServiceResult, Message, MessageType};
@ -224,7 +224,7 @@ where
}, },
State::ServiceCall(mut fut) => { State::ServiceCall(mut fut) => {
match fut.poll().map_err(DispatchError::Service)? { match fut.poll().map_err(DispatchError::Service)? {
Async::Ready(mut res) => { Async::Ready(res) => {
let (res, body) = res.replace_body(()); let (res, body) = res.replace_body(());
Some(self.send_response(res, body)?) Some(self.send_response(res, body)?)
} }

View File

@ -9,16 +9,15 @@ use bytes::{BufMut, Bytes, BytesMut};
use http::header::{ use http::header::{
HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING, HeaderValue, ACCEPT_ENCODING, CONNECTION, CONTENT_LENGTH, DATE, TRANSFER_ENCODING,
}; };
use http::{HeaderMap, StatusCode, Version}; use http::{HeaderMap, Method, StatusCode, Version};
use body::BodyLength; use crate::body::BodyLength;
use config::ServiceConfig; use crate::config::ServiceConfig;
use header::ContentEncoding; use crate::header::ContentEncoding;
use helpers; use crate::helpers;
use http::Method; use crate::message::{ConnectionType, RequestHead, ResponseHead};
use message::{ConnectionType, RequestHead, ResponseHead}; use crate::request::Request;
use request::Request; use crate::response::Response;
use response::Response;
const AVERAGE_HEADER_SIZE: usize = 30; const AVERAGE_HEADER_SIZE: usize = 30;
@ -205,7 +204,8 @@ impl MessageType for RequestHead {
Version::HTTP_11 => "HTTP/1.1", Version::HTTP_11 => "HTTP/1.1",
Version::HTTP_2 => "HTTP/2.0", Version::HTTP_2 => "HTTP/2.0",
} }
).map_err(|e| io::Error::new(io::ErrorKind::Other, e)) )
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
} }
} }

View File

@ -16,7 +16,7 @@ pub use self::codec::Codec;
pub use self::dispatcher::Dispatcher; pub use self::dispatcher::Dispatcher;
pub use self::service::{H1Service, H1ServiceHandler, OneRequest}; pub use self::service::{H1Service, H1ServiceHandler, OneRequest};
use request::Request; use crate::request::Request;
/// H1 service response type /// H1 service response type
pub enum H1ServiceResult<T> { pub enum H1ServiceResult<T> {

View File

@ -5,14 +5,15 @@ use std::net;
use actix_net::codec::Framed; use actix_net::codec::Framed;
use actix_net::service::{IntoNewService, NewService, Service}; use actix_net::service::{IntoNewService, NewService, Service};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll, Stream}; use futures::{try_ready, Async, Future, Poll, Stream};
use log::error;
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use body::MessageBody; use crate::body::MessageBody;
use config::{KeepAlive, ServiceConfig}; use crate::config::{KeepAlive, ServiceConfig};
use error::{DispatchError, ParseError}; use crate::error::{DispatchError, ParseError};
use request::Request; use crate::request::Request;
use response::Response; use crate::response::Response;
use super::codec::Codec; use super::codec::Codec;
use super::dispatcher::Dispatcher; use super::dispatcher::Dispatcher;
@ -174,9 +175,11 @@ where
pub fn server_address<U: net::ToSocketAddrs>(mut self, addr: U) -> Self { pub fn server_address<U: net::ToSocketAddrs>(mut self, addr: U) -> Self {
match addr.to_socket_addrs() { match addr.to_socket_addrs() {
Err(err) => error!("Can not convert to SocketAddr: {}", err), Err(err) => error!("Can not convert to SocketAddr: {}", err),
Ok(mut addrs) => if let Some(addr) = addrs.next() { Ok(mut addrs) => {
self.addr = addr; if let Some(addr) = addrs.next() {
}, self.addr = addr;
}
}
} }
self self
} }

View File

@ -1,13 +1,12 @@
//! Various http headers //! Various http headers
use bytes::Bytes; use bytes::Bytes;
pub use http::header::*;
use http::Error as HttpError;
use mime::Mime; use mime::Mime;
use modhttp::Error as HttpError;
pub use modhttp::header::*; use crate::error::ParseError;
use crate::httpmessage::HttpMessage;
use error::ParseError;
use httpmessage::HttpMessage;
#[doc(hidden)] #[doc(hidden)]
/// A trait for any object that will represent a header field and value. /// A trait for any object that will represent a header field and value.

View File

@ -1,7 +1,8 @@
//! Basic http responses //! Basic http responses
#![allow(non_upper_case_globals)] #![allow(non_upper_case_globals)]
use http::StatusCode; use http::StatusCode;
use response::{Response, ResponseBuilder};
use crate::response::{Response, ResponseBuilder};
macro_rules! STATIC_RESP { macro_rules! STATIC_RESP {
($name:ident, $status:expr) => { ($name:ident, $status:expr) => {

View File

@ -10,11 +10,11 @@ use serde::de::DeserializeOwned;
use serde_urlencoded; use serde_urlencoded;
use std::str; use std::str;
use error::{ use crate::error::{
ContentTypeError, ParseError, PayloadError, ReadlinesError, UrlencodedError, ContentTypeError, ParseError, PayloadError, ReadlinesError, UrlencodedError,
}; };
use header::Header; use crate::header::Header;
use json::JsonBody; use crate::json::JsonBody;
/// Trait that implements general purpose operations on http messages /// Trait that implements general purpose operations on http messages
pub trait HttpMessage: Sized { pub trait HttpMessage: Sized {
@ -438,7 +438,8 @@ where
body.extend_from_slice(&chunk); body.extend_from_slice(&chunk);
Ok(body) Ok(body)
} }
}).map(|body| body.freeze()), })
.map(|body| body.freeze()),
)); ));
self.poll() self.poll()
} }
@ -546,7 +547,8 @@ where
body.extend_from_slice(&chunk); body.extend_from_slice(&chunk);
Ok(body) Ok(body)
} }
}).and_then(move |body| { })
.and_then(move |body| {
if (encoding as *const Encoding) == UTF_8 { if (encoding as *const Encoding) == UTF_8 {
serde_urlencoded::from_bytes::<U>(&body) serde_urlencoded::from_bytes::<U>(&body)
.map_err(|_| UrlencodedError::Parse) .map_err(|_| UrlencodedError::Parse)
@ -604,7 +606,8 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
"content-type", "content-type",
"applicationadfadsfasdflknadsfklnadsfjson", "applicationadfadsfasdflknadsfklnadsfjson",
).finish(); )
.finish();
assert_eq!(Err(ContentTypeError::ParseError), req.mime_type()); assert_eq!(Err(ContentTypeError::ParseError), req.mime_type());
} }
@ -619,7 +622,8 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
"content-type", "content-type",
"application/json; charset=ISO-8859-2", "application/json; charset=ISO-8859-2",
).finish(); )
.finish();
assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name()); assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name());
} }
@ -631,7 +635,8 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
"content-type", "content-type",
"application/json; charset=kkkttktk", "application/json; charset=kkkttktk",
).finish(); )
.finish();
assert_eq!( assert_eq!(
Some(ContentTypeError::UnknownEncoding), Some(ContentTypeError::UnknownEncoding),
req.encoding().err() req.encoding().err()
@ -651,7 +656,8 @@ mod tests {
.header( .header(
header::TRANSFER_ENCODING, header::TRANSFER_ENCODING,
Bytes::from_static(b"some va\xadscc\xacas0xsdasdlue"), Bytes::from_static(b"some va\xadscc\xacas0xsdasdlue"),
).finish(); )
.finish();
assert!(req.chunked().is_err()); assert!(req.chunked().is_err());
} }
@ -689,7 +695,8 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/x-www-form-urlencoded", "application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "xxxx") )
.header(header::CONTENT_LENGTH, "xxxx")
.finish(); .finish();
assert_eq!( assert_eq!(
req.urlencoded::<Info>().poll().err().unwrap(), req.urlencoded::<Info>().poll().err().unwrap(),
@ -699,7 +706,8 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/x-www-form-urlencoded", "application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "1000000") )
.header(header::CONTENT_LENGTH, "1000000")
.finish(); .finish();
assert_eq!( assert_eq!(
req.urlencoded::<Info>().poll().err().unwrap(), req.urlencoded::<Info>().poll().err().unwrap(),
@ -720,7 +728,8 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/x-www-form-urlencoded", "application/x-www-form-urlencoded",
).header(header::CONTENT_LENGTH, "11") )
.header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
.finish(); .finish();
@ -735,7 +744,8 @@ mod tests {
let req = TestRequest::with_header( let req = TestRequest::with_header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
"application/x-www-form-urlencoded; charset=utf-8", "application/x-www-form-urlencoded; charset=utf-8",
).header(header::CONTENT_LENGTH, "11") )
.header(header::CONTENT_LENGTH, "11")
.set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
.finish(); .finish();
@ -786,7 +796,8 @@ mod tests {
b"Lorem Ipsum is simply dummy text of the printing and typesetting\n\ b"Lorem Ipsum is simply dummy text of the printing and typesetting\n\
industry. Lorem Ipsum has been the industry's standard dummy\n\ industry. Lorem Ipsum has been the industry's standard dummy\n\
Contrary to popular belief, Lorem Ipsum is not simply random text.", Contrary to popular belief, Lorem Ipsum is not simply random text.",
)).finish(); ))
.finish();
let mut r = Readlines::new(&req); let mut r = Readlines::new(&req);
match r.poll().ok().unwrap() { match r.poll().ok().unwrap() {
Async::Ready(Some(s)) => assert_eq!( Async::Ready(Some(s)) => assert_eq!(

View File

@ -6,8 +6,8 @@ use mime;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use serde_json; use serde_json;
use error::JsonPayloadError; use crate::error::JsonPayloadError;
use httpmessage::HttpMessage; use crate::httpmessage::HttpMessage;
/// Request payload json parser that resolves to a deserialized `T` value. /// Request payload json parser that resolves to a deserialized `T` value.
/// ///
@ -124,7 +124,8 @@ impl<T: HttpMessage + 'static, U: DeserializeOwned + 'static> Future for JsonBod
body.extend_from_slice(&chunk); body.extend_from_slice(&chunk);
Ok(body) Ok(body)
} }
}).and_then(|body| Ok(serde_json::from_slice::<U>(&body)?)); })
.and_then(|body| Ok(serde_json::from_slice::<U>(&body)?));
self.fut = Some(Box::new(fut)); self.fut = Some(Box::new(fut));
self.poll() self.poll()
} }
@ -170,7 +171,8 @@ mod tests {
.header( .header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
header::HeaderValue::from_static("application/text"), header::HeaderValue::from_static("application/text"),
).finish(); )
.finish();
let mut json = req.json::<MyObject>(); let mut json = req.json::<MyObject>();
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType); assert_eq!(json.poll().err().unwrap(), JsonPayloadError::ContentType);
@ -178,10 +180,12 @@ mod tests {
.header( .header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"), header::HeaderValue::from_static("application/json"),
).header( )
.header(
header::CONTENT_LENGTH, header::CONTENT_LENGTH,
header::HeaderValue::from_static("10000"), header::HeaderValue::from_static("10000"),
).finish(); )
.finish();
let mut json = req.json::<MyObject>().limit(100); let mut json = req.json::<MyObject>().limit(100);
assert_eq!(json.poll().err().unwrap(), JsonPayloadError::Overflow); assert_eq!(json.poll().err().unwrap(), JsonPayloadError::Overflow);
@ -189,10 +193,12 @@ mod tests {
.header( .header(
header::CONTENT_TYPE, header::CONTENT_TYPE,
header::HeaderValue::from_static("application/json"), header::HeaderValue::from_static("application/json"),
).header( )
.header(
header::CONTENT_LENGTH, header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"), header::HeaderValue::from_static("16"),
).set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) )
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
.finish(); .finish();
let mut json = req.json::<MyObject>(); let mut json = req.json::<MyObject>();

View File

@ -62,56 +62,12 @@
// #![warn(missing_docs)] // #![warn(missing_docs)]
#![allow(dead_code)] #![allow(dead_code)]
extern crate actix;
extern crate actix_net;
#[macro_use]
extern crate log;
extern crate base64;
extern crate byteorder;
extern crate bytes;
extern crate sha1;
extern crate time;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate futures;
extern crate cookie;
extern crate encoding;
extern crate http as modhttp;
extern crate httparse;
extern crate indexmap;
extern crate mime;
extern crate net2;
extern crate percent_encoding;
extern crate rand;
extern crate serde;
extern crate serde_json;
extern crate serde_urlencoded;
extern crate slab;
extern crate tokio;
extern crate tokio_codec;
extern crate tokio_current_thread;
extern crate tokio_io;
extern crate tokio_tcp;
extern crate tokio_timer;
extern crate trust_dns_proto;
extern crate trust_dns_resolver;
extern crate url as urlcrate;
#[cfg(test)]
#[macro_use]
extern crate serde_derive;
#[cfg(feature = "ssl")]
extern crate openssl;
pub mod body; pub mod body;
pub mod client; pub mod client;
mod config; mod config;
mod extensions; mod extensions;
mod header; mod header;
mod helpers;
mod httpcodes; mod httpcodes;
mod httpmessage; mod httpmessage;
mod json; mod json;
@ -123,18 +79,17 @@ mod service;
pub mod error; pub mod error;
pub mod h1; pub mod h1;
pub(crate) mod helpers;
pub mod test; pub mod test;
pub mod ws; pub mod ws;
pub use body::{Body, MessageBody};
pub use error::{Error, ResponseError, Result};
pub use extensions::Extensions;
pub use httpmessage::HttpMessage;
pub use request::Request;
pub use response::Response;
pub use service::{SendError, SendResponse};
pub use self::body::{Body, MessageBody};
pub use self::config::{KeepAlive, ServiceConfig, ServiceConfigBuilder}; pub use self::config::{KeepAlive, ServiceConfig, ServiceConfigBuilder};
pub use self::error::{Error, ResponseError, Result};
pub use self::extensions::Extensions;
pub use self::httpmessage::HttpMessage;
pub use self::request::Request;
pub use self::response::Response;
pub use self::service::{SendError, SendResponse};
pub mod dev { pub mod dev {
//! The `actix-web` prelude for library developers //! The `actix-web` prelude for library developers
@ -147,31 +102,31 @@ pub mod dev {
//! use actix_http::dev::*; //! use actix_http::dev::*;
//! ``` //! ```
pub use httpmessage::{MessageBody, Readlines, UrlEncoded}; pub use crate::httpmessage::{MessageBody, Readlines, UrlEncoded};
pub use json::JsonBody; pub use crate::json::JsonBody;
pub use payload::{Payload, PayloadBuffer}; pub use crate::payload::{Payload, PayloadBuffer};
pub use response::ResponseBuilder; pub use crate::response::ResponseBuilder;
} }
pub mod http { pub mod http {
//! Various HTTP related types //! Various HTTP related types
// re-exports // re-exports
pub use modhttp::header::{HeaderName, HeaderValue}; pub use http::header::{HeaderName, HeaderValue};
pub use modhttp::{Method, StatusCode, Version}; pub use http::{Method, StatusCode, Version};
#[doc(hidden)] #[doc(hidden)]
pub use modhttp::{uri, Error, HeaderMap, HttpTryFrom, Uri}; pub use http::{uri, Error, HeaderMap, HttpTryFrom, Uri};
#[doc(hidden)] #[doc(hidden)]
pub use modhttp::uri::PathAndQuery; pub use http::uri::PathAndQuery;
pub use cookie::{Cookie, CookieBuilder}; pub use cookie::{Cookie, CookieBuilder};
/// Various http headers /// Various http headers
pub mod header { pub mod header {
pub use header::*; pub use crate::header::*;
} }
pub use header::ContentEncoding; pub use crate::header::ContentEncoding;
pub use message::ConnectionType; pub use crate::message::ConnectionType;
} }

View File

@ -4,8 +4,8 @@ use std::rc::Rc;
use http::{HeaderMap, Method, StatusCode, Uri, Version}; use http::{HeaderMap, Method, StatusCode, Uri, Version};
use extensions::Extensions; use crate::extensions::Extensions;
use payload::Payload; use crate::payload::Payload;
/// Represents various types of connection /// Represents various types of connection
#[derive(Copy, Clone, PartialEq, Debug)] #[derive(Copy, Clone, PartialEq, Debug)]

View File

@ -9,7 +9,7 @@ use std::cmp;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::rc::{Rc, Weak}; use std::rc::{Rc, Weak};
use error::PayloadError; use crate::error::PayloadError;
/// max buffer size 32k /// max buffer size 32k
pub(crate) const MAX_BUFFER_SIZE: usize = 32_768; pub(crate) const MAX_BUFFER_SIZE: usize = 32_768;
@ -515,7 +515,8 @@ where
.fold(BytesMut::new(), |mut b, c| { .fold(BytesMut::new(), |mut b, c| {
b.extend_from_slice(c); b.extend_from_slice(c);
b b
}).freeze() })
.freeze()
} }
} }
@ -547,7 +548,8 @@ mod tests {
let res: Result<(), ()> = Ok(()); let res: Result<(), ()> = Ok(());
result(res) result(res)
})).unwrap(); }))
.unwrap();
} }
#[test] #[test]
@ -571,7 +573,8 @@ mod tests {
let res: Result<(), ()> = Ok(()); let res: Result<(), ()> = Ok(());
result(res) result(res)
})).unwrap(); }))
.unwrap();
} }
#[test] #[test]
@ -588,7 +591,8 @@ mod tests {
payload.readany().err().unwrap(); payload.readany().err().unwrap();
let res: Result<(), ()> = Ok(()); let res: Result<(), ()> = Ok(());
result(res) result(res)
})).unwrap(); }))
.unwrap();
} }
#[test] #[test]
@ -616,7 +620,8 @@ mod tests {
let res: Result<(), ()> = Ok(()); let res: Result<(), ()> = Ok(());
result(res) result(res)
})).unwrap(); }))
.unwrap();
} }
#[test] #[test]
@ -649,7 +654,8 @@ mod tests {
let res: Result<(), ()> = Ok(()); let res: Result<(), ()> = Ok(());
result(res) result(res)
})).unwrap(); }))
.unwrap();
} }
#[test] #[test]
@ -682,7 +688,8 @@ mod tests {
let res: Result<(), ()> = Ok(()); let res: Result<(), ()> = Ok(());
result(res) result(res)
})).unwrap(); }))
.unwrap();
} }
#[test] #[test]
@ -703,6 +710,7 @@ mod tests {
let res: Result<(), ()> = Ok(()); let res: Result<(), ()> = Ok(());
result(res) result(res)
})).unwrap(); }))
.unwrap();
} }
} }

View File

@ -4,11 +4,10 @@ use std::rc::Rc;
use http::{header, HeaderMap, Method, Uri, Version}; use http::{header, HeaderMap, Method, Uri, Version};
use extensions::Extensions; use crate::extensions::Extensions;
use httpmessage::HttpMessage; use crate::httpmessage::HttpMessage;
use payload::Payload; use crate::message::{Message, MessagePool, RequestHead};
use crate::payload::Payload;
use message::{Message, MessagePool, RequestHead};
/// Request /// Request
pub struct Request { pub struct Request {

View File

@ -12,10 +12,10 @@ use http::{Error as HttpError, HeaderMap, HttpTryFrom, StatusCode, Version};
use serde::Serialize; use serde::Serialize;
use serde_json; use serde_json;
use body::{Body, BodyStream, MessageBody, ResponseBody}; use crate::body::{Body, BodyStream, MessageBody, ResponseBody};
use error::Error; use crate::error::Error;
use header::{Header, IntoHeaderValue}; use crate::header::{Header, IntoHeaderValue};
use message::{ConnectionType, Head, ResponseHead}; use crate::message::{ConnectionType, Head, ResponseHead};
/// max write buffer size 64k /// max write buffer size 64k
pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536; pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536;
@ -161,7 +161,8 @@ impl<B: MessageBody> Response<B> {
HeaderValue::from_str(&cookie.to_string()) HeaderValue::from_str(&cookie.to_string())
.map(|c| { .map(|c| {
h.append(header::SET_COOKIE, c); h.append(header::SET_COOKIE, c);
}).map_err(|e| e.into()) })
.map_err(|e| e.into())
} }
/// Remove all cookies with the given name from this response. Returns /// Remove all cookies with the given name from this response. Returns

View File

@ -6,10 +6,10 @@ use futures::future::{ok, Either, FutureResult};
use futures::{Async, Future, Poll, Sink}; use futures::{Async, Future, Poll, Sink};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use body::{BodyLength, MessageBody, ResponseBody}; use crate::body::{BodyLength, MessageBody, ResponseBody};
use error::{Error, ResponseError}; use crate::error::{Error, ResponseError};
use h1::{Codec, Message}; use crate::h1::{Codec, Message};
use response::Response; use crate::response::Response;
pub struct SendError<T, R, E>(PhantomData<(T, R, E)>); pub struct SendError<T, R, E>(PhantomData<(T, R, E)>);
@ -56,7 +56,7 @@ where
match req { match req {
Ok(r) => Either::A(ok(r)), Ok(r) => Either::A(ok(r)),
Err((e, framed)) => { Err((e, framed)) => {
let mut res = e.error_response().set_body(format!("{}", e)); let res = e.error_response().set_body(format!("{}", e));
let (res, _body) = res.replace_body(()); let (res, _body) = res.replace_body(());
Either::B(SendErrorFut { Either::B(SendErrorFut {
framed: Some(framed), framed: Some(framed),
@ -206,11 +206,13 @@ where
// flush write buffer // flush write buffer
if !framed.is_write_buf_empty() { if !framed.is_write_buf_empty() {
match framed.poll_complete()? { match framed.poll_complete()? {
Async::Ready(_) => if body_ready { Async::Ready(_) => {
continue; if body_ready {
} else { continue;
return Ok(Async::NotReady); } else {
}, return Ok(Async::NotReady);
}
}
Async::NotReady => return Ok(Async::NotReady), Async::NotReady => return Ok(Async::NotReady),
} }
} }

View File

@ -17,15 +17,15 @@ use net2::TcpBuilder;
use tokio::runtime::current_thread::Runtime; use tokio::runtime::current_thread::Runtime;
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use body::MessageBody; use crate::body::MessageBody;
use client::{ use crate::client::{
ClientRequest, ClientRequestBuilder, ClientResponse, Connect, Connection, Connector, ClientRequest, ClientRequestBuilder, ClientResponse, Connect, Connection, Connector,
ConnectorError, SendRequestError, ConnectorError, SendRequestError,
}; };
use header::{Header, IntoHeaderValue}; use crate::header::{Header, IntoHeaderValue};
use payload::Payload; use crate::payload::Payload;
use request::Request; use crate::request::Request;
use ws; use crate::ws;
/// Test `Request` builder /// Test `Request` builder
/// ///
@ -338,7 +338,7 @@ impl TestServer {
} }
fn new_connector( fn new_connector(
) -> impl Service<Connect, Response = impl Connection, Error = ConnectorError> + Clone ) -> impl Service<Connect, Response = impl Connection, Error = ConnectorError> + Clone
{ {
#[cfg(feature = "ssl")] #[cfg(feature = "ssl")]
{ {

View File

@ -5,10 +5,9 @@ use cookie::Cookie;
use http::header::{HeaderName, HeaderValue}; use http::header::{HeaderName, HeaderValue};
use http::{Error as HttpError, HttpTryFrom}; use http::{Error as HttpError, HttpTryFrom};
use client::{ClientRequest, ClientRequestBuilder};
use header::IntoHeaderValue;
use super::ClientError; use super::ClientError;
use crate::client::{ClientRequest, ClientRequestBuilder};
use crate::header::IntoHeaderValue;
/// `WebSocket` connection /// `WebSocket` connection
pub struct Connect { pub struct Connect {

View File

@ -2,12 +2,11 @@
use std::io; use std::io;
use actix_net::connector::ConnectorError; use actix_net::connector::ConnectorError;
use http::header::HeaderValue; use failure::Fail;
use http::StatusCode; use http::{header::HeaderValue, Error as HttpError, StatusCode};
use error::ParseError; use crate::error::ParseError;
use http::Error as HttpError; use crate::ws::ProtocolError;
use ws::ProtocolError;
/// Websocket client error /// Websocket client error
#[derive(Fail, Debug)] #[derive(Fail, Debug)]

View File

@ -6,17 +6,18 @@ use actix_net::connector::{Connect as TcpConnect, ConnectorError, DefaultConnect
use actix_net::service::Service; use actix_net::service::Service;
use base64; use base64;
use futures::future::{err, Either, FutureResult}; use futures::future::{err, Either, FutureResult};
use futures::{Async, Future, Poll, Sink, Stream}; use futures::{try_ready, Async, Future, Poll, Sink, Stream};
use http::header::{self, HeaderValue}; use http::header::{self, HeaderValue};
use http::{HttpTryFrom, StatusCode}; use http::{HttpTryFrom, StatusCode};
use log::trace;
use rand; use rand;
use sha1::Sha1; use sha1::Sha1;
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use body::BodyLength; use crate::body::BodyLength;
use client::ClientResponse; use crate::client::ClientResponse;
use h1; use crate::h1;
use ws::Codec; use crate::ws::Codec;
use super::{ClientError, Connect, Protocol}; use super::{ClientError, Connect, Protocol};

View File

@ -1,10 +1,11 @@
use byteorder::{ByteOrder, LittleEndian, NetworkEndian}; use byteorder::{ByteOrder, LittleEndian, NetworkEndian};
use bytes::{BufMut, Bytes, BytesMut}; use bytes::{BufMut, Bytes, BytesMut};
use log::debug;
use rand; use rand;
use ws::mask::apply_mask; use crate::ws::mask::apply_mask;
use ws::proto::{CloseCode, CloseReason, OpCode}; use crate::ws::proto::{CloseCode, CloseReason, OpCode};
use ws::ProtocolError; use crate::ws::ProtocolError;
/// A struct representing a `WebSocket` frame. /// A struct representing a `WebSocket` frame.
#[derive(Debug)] #[derive(Debug)]

View File

@ -5,10 +5,12 @@
//! communicate with the peer. //! communicate with the peer.
use std::io; use std::io;
use error::ResponseError; use failure::Fail;
use http::{header, Method, StatusCode}; use http::{header, Method, StatusCode};
use request::Request;
use response::{Response, ResponseBuilder}; use crate::error::ResponseError;
use crate::request::Request;
use crate::response::{Response, ResponseBuilder};
mod client; mod client;
mod codec; mod codec;
@ -221,7 +223,8 @@ mod tests {
.header( .header(
header::UPGRADE, header::UPGRADE,
header::HeaderValue::from_static("websocket"), header::HeaderValue::from_static("websocket"),
).finish(); )
.finish();
assert_eq!( assert_eq!(
HandshakeError::NoConnectionUpgrade, HandshakeError::NoConnectionUpgrade,
verify_handshake(&req).err().unwrap() verify_handshake(&req).err().unwrap()
@ -231,10 +234,12 @@ mod tests {
.header( .header(
header::UPGRADE, header::UPGRADE,
header::HeaderValue::from_static("websocket"), header::HeaderValue::from_static("websocket"),
).header( )
.header(
header::CONNECTION, header::CONNECTION,
header::HeaderValue::from_static("upgrade"), header::HeaderValue::from_static("upgrade"),
).finish(); )
.finish();
assert_eq!( assert_eq!(
HandshakeError::NoVersionHeader, HandshakeError::NoVersionHeader,
verify_handshake(&req).err().unwrap() verify_handshake(&req).err().unwrap()
@ -244,13 +249,16 @@ mod tests {
.header( .header(
header::UPGRADE, header::UPGRADE,
header::HeaderValue::from_static("websocket"), header::HeaderValue::from_static("websocket"),
).header( )
.header(
header::CONNECTION, header::CONNECTION,
header::HeaderValue::from_static("upgrade"), header::HeaderValue::from_static("upgrade"),
).header( )
.header(
header::SEC_WEBSOCKET_VERSION, header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("5"), header::HeaderValue::from_static("5"),
).finish(); )
.finish();
assert_eq!( assert_eq!(
HandshakeError::UnsupportedVersion, HandshakeError::UnsupportedVersion,
verify_handshake(&req).err().unwrap() verify_handshake(&req).err().unwrap()
@ -260,13 +268,16 @@ mod tests {
.header( .header(
header::UPGRADE, header::UPGRADE,
header::HeaderValue::from_static("websocket"), header::HeaderValue::from_static("websocket"),
).header( )
.header(
header::CONNECTION, header::CONNECTION,
header::HeaderValue::from_static("upgrade"), header::HeaderValue::from_static("upgrade"),
).header( )
.header(
header::SEC_WEBSOCKET_VERSION, header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"), header::HeaderValue::from_static("13"),
).finish(); )
.finish();
assert_eq!( assert_eq!(
HandshakeError::BadWebsocketKey, HandshakeError::BadWebsocketKey,
verify_handshake(&req).err().unwrap() verify_handshake(&req).err().unwrap()
@ -276,16 +287,20 @@ mod tests {
.header( .header(
header::UPGRADE, header::UPGRADE,
header::HeaderValue::from_static("websocket"), header::HeaderValue::from_static("websocket"),
).header( )
.header(
header::CONNECTION, header::CONNECTION,
header::HeaderValue::from_static("upgrade"), header::HeaderValue::from_static("upgrade"),
).header( )
.header(
header::SEC_WEBSOCKET_VERSION, header::SEC_WEBSOCKET_VERSION,
header::HeaderValue::from_static("13"), header::HeaderValue::from_static("13"),
).header( )
.header(
header::SEC_WEBSOCKET_KEY, header::SEC_WEBSOCKET_KEY,
header::HeaderValue::from_static("13"), header::HeaderValue::from_static("13"),
).finish(); )
.finish();
assert_eq!( assert_eq!(
StatusCode::SWITCHING_PROTOCOLS, StatusCode::SWITCHING_PROTOCOLS,
handshake_response(&req).finish().status() handshake_response(&req).finish().status()

View File

@ -5,8 +5,8 @@ use actix_net::service::{NewService, Service};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, IntoFuture, Poll}; use futures::{Async, IntoFuture, Poll};
use h1::Codec; use crate::h1::Codec;
use request::Request; use crate::request::Request;
use super::{verify_handshake, HandshakeError}; use super::{verify_handshake, HandshakeError};

View File

@ -91,7 +91,8 @@ fn test_with_query_parameter() {
} else { } else {
ok::<_, ()>(Response::BadRequest().finish()) ok::<_, ()>(Response::BadRequest().finish())
} }
}).map(|_| ()) })
.map(|_| ())
}); });
let mut connector = srv.new_connector(); let mut connector = srv.new_connector();

View File

@ -209,7 +209,8 @@ fn test_content_length() {
StatusCode::NOT_FOUND, StatusCode::NOT_FOUND,
]; ];
future::ok::<_, ()>(Response::new(statuses[indx])) future::ok::<_, ()>(Response::new(statuses[indx]))
}).map(|_| ()) })
.map(|_| ())
}); });
let header = HeaderName::from_static("content-length"); let header = HeaderName::from_static("content-length");
@ -348,7 +349,8 @@ fn test_head_binary() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = test::TestServer::with_factory(|| {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR)) ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR))
}).map(|_| ()) })
.map(|_| ())
}); });
let req = client::ClientRequest::head(srv.url("/")).finish().unwrap(); let req = client::ClientRequest::head(srv.url("/")).finish().unwrap();
@ -396,7 +398,8 @@ fn test_body_length() {
Response::Ok() Response::Ok()
.body(Body::from_message(body::SizedStream::new(STR.len(), body))), .body(Body::from_message(body::SizedStream::new(STR.len(), body))),
) )
}).map(|_| ()) })
.map(|_| ())
}); });
let req = srv.get().finish().unwrap(); let req = srv.get().finish().unwrap();
@ -414,7 +417,8 @@ fn test_body_chunked_explicit() {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref()))); let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().streaming(body)) ok::<_, ()>(Response::Ok().streaming(body))
}).map(|_| ()) })
.map(|_| ())
}); });
let req = srv.get().finish().unwrap(); let req = srv.get().finish().unwrap();
@ -434,7 +438,8 @@ fn test_body_chunked_implicit() {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref()))); let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().streaming(body)) ok::<_, ()>(Response::Ok().streaming(body))
}).map(|_| ()) })
.map(|_| ())
}); });
let req = srv.get().finish().unwrap(); let req = srv.get().finish().unwrap();
@ -456,7 +461,8 @@ fn test_response_http_error_handling() {
.header(http::header::CONTENT_TYPE, broken_header) .header(http::header::CONTENT_TYPE, broken_header)
.body(STR), .body(STR),
) )
}).map(|_| ()) })
.map(|_| ())
}); });
let req = srv.get().finish().unwrap(); let req = srv.get().finish().unwrap();

View File

@ -62,7 +62,8 @@ fn test_simple() {
SendResponse::send( SendResponse::send(
framed, framed,
ws::handshake_response(&req).finish(), ws::handshake_response(&req).finish(),
).map_err(|_| ()) )
.map_err(|_| ())
.and_then(|framed| { .and_then(|framed| {
// start websocket service // start websocket service
let framed = framed.into_framed(ws::Codec::new()); let framed = framed.into_framed(ws::Codec::new());