feat(lib): implement compatibility with http crate

This commit is contained in:
Sam Rijs
2017-09-23 05:07:57 +10:00
committed by Sean McArthur
parent 92595e84a2
commit 0c7d375ba3
17 changed files with 535 additions and 1 deletions

6
src/client/compat.rs Normal file
View File

@@ -0,0 +1,6 @@
//! Wrappers to build compatibility with the `http` crate.
pub use super::compat_impl::{
CompatClient,
CompatFutureResponse
};

53
src/client/compat_impl.rs Normal file
View File

@@ -0,0 +1,53 @@
use futures::{Future, Poll, Stream};
use http_types;
use tokio_service::Service;
use client::{Connect, Client, FutureResponse};
use error::Error;
use http::Body;
/// A Client to make outgoing HTTP requests.
#[derive(Debug)]
pub struct CompatClient<C, B = Body> {
inner: Client<C, B>
}
pub fn client<C, B>(client: Client<C, B>) -> CompatClient<C, B> {
CompatClient { inner: client }
}
impl<C, B> Service for CompatClient<C, B>
where C: Connect,
B: Stream<Error=Error> + 'static,
B::Item: AsRef<[u8]>,
{
type Request = http_types::Request<B>;
type Response = http_types::Response<Body>;
type Error = Error;
type Future = CompatFutureResponse;
fn call(&self, req: Self::Request) -> Self::Future {
future(self.inner.call(req.into()))
}
}
/// A `Future` that will resolve to an `http::Response`.
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct CompatFutureResponse {
inner: FutureResponse
}
pub fn future(fut: FutureResponse) -> CompatFutureResponse {
CompatFutureResponse { inner: fut }
}
impl Future for CompatFutureResponse {
type Item = http_types::Response<Body>;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Error> {
self.inner.poll()
.map(|a| a.map(|r| r.into()))
}
}

View File

@@ -9,6 +9,8 @@ use std::time::Duration;
use futures::{future, Poll, Async, Future, Stream};
use futures::unsync::oneshot;
#[cfg(feature = "compat")]
use http_types;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio::reactor::Handle;
use tokio_proto::BindClient;
@@ -33,6 +35,10 @@ pub use self::connect::{HttpConnector, Connect};
mod connect;
mod dns;
mod pool;
#[cfg(feature = "compat")]
mod compat_impl;
#[cfg(feature = "compat")]
pub mod compat;
/// A Client to make outgoing HTTP requests.
// If the Connector is clone, then the Client can be clone easily.
@@ -108,6 +114,19 @@ where C: Connect,
pub fn request(&self, req: Request<B>) -> FutureResponse {
self.call(req)
}
/// Send an `http::Request` using this Client.
#[inline]
#[cfg(feature = "compat")]
pub fn request_compat(&self, req: http_types::Request<B>) -> compat::CompatFutureResponse {
self::compat_impl::future(self.call(req.into()))
}
/// Convert into a client accepting `http::Request`.
#[cfg(feature = "compat")]
pub fn into_compat(self) -> compat::CompatClient<C, B> {
self::compat_impl::client(self)
}
}
/// A `Future` that will resolve to an HTTP Response.