Skip to content

Commit

Permalink
feat(lib): remove extern Url type usage
Browse files Browse the repository at this point in the history
BREAKING CHANGE: The `Url` type is no longer used. Any instance in the
  `Client` API has had it replaced with `hyper::Uri`.

  This also means `Error::Uri` has changed types to
  `hyper::error::UriError`.

  The type `hyper::header::parsing::HTTP_VALUE` has been made private,
  as an implementation detail. The function `http_percent_encoding`
  should be used instead.
  • Loading branch information
seanmonstar committed Mar 21, 2017
1 parent e81184e commit 4fb7e6e
Show file tree
Hide file tree
Showing 12 changed files with 188 additions and 151 deletions.
4 changes: 2 additions & 2 deletions benches/end_to_end.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fn get_one_at_a_time(b: &mut test::Bencher) {

let client = hyper::Client::new(&handle);

let url: hyper::Url = format!("http://{}/get", addr).parse().unwrap();
let url: hyper::Uri = format!("http://{}/get", addr).parse().unwrap();

b.bytes = 160 * 2 + PHRASE.len() as u64;
b.iter(move || {
Expand All @@ -51,7 +51,7 @@ fn post_one_at_a_time(b: &mut test::Bencher) {

let client = hyper::Client::new(&handle);

let url: hyper::Url = format!("http://{}/get", addr).parse().unwrap();
let url: hyper::Uri = format!("http://{}/get", addr).parse().unwrap();

let post = "foo bar baz quux";
b.bytes = 180 * 2 + post.len() as u64 + PHRASE.len() as u64;
Expand Down
4 changes: 2 additions & 2 deletions examples/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ fn main() {
}
};

let url = hyper::Url::parse(&url).unwrap();
if url.scheme() != "http" {
let url = url.parse::<hyper::Uri>().unwrap();
if url.scheme() != Some("http") {
println!("This example only works with 'http' URLs.");
return;
}
Expand Down
23 changes: 11 additions & 12 deletions src/client/connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,33 @@ use tokio_io::{AsyncRead, AsyncWrite};
use tokio::reactor::Handle;
use tokio::net::{TcpStream, TcpStreamNew};
use tokio_service::Service;
use Url;
use Uri;

use super::dns;

/// A connector creates an Io to a remote address..
///
/// This trait is not implemented directly, and only exists to make
/// the intent clearer. A connector should implement `Service` with
/// `Request=Url` and `Response: Io` instead.
pub trait Connect: Service<Request=Url, Error=io::Error> + 'static {
/// `Request=Uri` and `Response: Io` instead.
pub trait Connect: Service<Request=Uri, Error=io::Error> + 'static {
/// The connected Io Stream.
type Output: AsyncRead + AsyncWrite + 'static;
/// A Future that will resolve to the connected Stream.
type Future: Future<Item=Self::Output, Error=io::Error> + 'static;
/// Connect to a remote address.
fn connect(&self, Url) -> <Self as Connect>::Future;
fn connect(&self, Uri) -> <Self as Connect>::Future;
}

impl<T> Connect for T
where T: Service<Request=Url, Error=io::Error> + 'static,
where T: Service<Request=Uri, Error=io::Error> + 'static,
T::Response: AsyncRead + AsyncWrite,
T::Future: Future<Error=io::Error>,
{
type Output = T::Response;
type Future = T::Future;

fn connect(&self, url: Url) -> <Self as Connect>::Future {
fn connect(&self, url: Uri) -> <Self as Connect>::Future {
self.call(url)
}
}
Expand Down Expand Up @@ -66,21 +66,21 @@ impl fmt::Debug for HttpConnector {
}

impl Service for HttpConnector {
type Request = Url;
type Request = Uri;
type Response = TcpStream;
type Error = io::Error;
type Future = HttpConnecting;

fn call(&self, url: Url) -> Self::Future {
fn call(&self, url: Uri) -> Self::Future {
debug!("Http::connect({:?})", url);
let host = match url.host_str() {
let host = match url.host() {
Some(s) => s,
None => return HttpConnecting {
state: State::Error(Some(io::Error::new(io::ErrorKind::InvalidInput, "invalid url"))),
handle: self.handle.clone(),
},
};
let port = url.port_or_known_default().unwrap_or(80);
let port = url.port().unwrap_or(80);

HttpConnecting {
state: State::Resolving(self.dns.resolve(host.into(), port)),
Expand Down Expand Up @@ -185,13 +185,12 @@ impl<S: SslClient> HttpsConnector<S> {
mod tests {
use std::io;
use tokio::reactor::Core;
use Url;
use super::{Connect, HttpConnector};

#[test]
fn test_non_http_url() {
let mut core = Core::new().unwrap();
let url = Url::parse("file:///home/sean/foo.txt").unwrap();
let url = "/foo/bar?baz".parse().unwrap();
let connector = HttpConnector::new(1, &core.handle());

assert_eq!(core.run(connector.connect(url)).unwrap_err().kind(), io::ErrorKind::InvalidInput);
Expand Down
26 changes: 19 additions & 7 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::marker::PhantomData;
use std::rc::Rc;
use std::time::Duration;

use futures::{Poll, Async, Future, Stream};
use futures::{future, Poll, Async, Future, Stream};
use futures::unsync::oneshot;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio::reactor::Handle;
Expand All @@ -24,7 +24,7 @@ use header::{Headers, Host};
use http::{self, TokioBody};
use method::Method;
use self::pool::{Pool, Pooled};
use Url;
use uri::{self, Uri};

pub use self::connect::{HttpConnector, Connect};
pub use self::request::Request;
Expand Down Expand Up @@ -95,7 +95,7 @@ where C: Connect,
{
/// Send a GET Request using this Client.
#[inline]
pub fn get(&self, url: Url) -> FutureResponse {
pub fn get(&self, url: Uri) -> FutureResponse {
self.request(Request::new(Method::Get, url))
}

Expand Down Expand Up @@ -135,18 +135,30 @@ where C: Connect,
type Future = FutureResponse;

fn call(&self, req: Self::Request) -> Self::Future {
let url = req.url().clone();
let url = req.uri().clone();
let domain = match uri::scheme_and_authority(&url) {
Some(uri) => uri,
None => {
return FutureResponse(Box::new(future::err(::Error::Io(
io::Error::new(
io::ErrorKind::InvalidInput,
"invalid URI for Client Request"
)
))));
}
};
let host = Host::new(domain.host().expect("authority implies host").to_owned(), domain.port());
let (mut head, body) = request::split(req);
let mut headers = Headers::new();
headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port()));
headers.set(host);
headers.extend(head.headers.iter());
head.headers = headers;

let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]);
let checkout = self.pool.checkout(domain.as_ref());
let connect = {
let handle = self.handle.clone();
let pool = self.pool.clone();
let pool_key = Rc::new(url[..::url::Position::BeforePath].to_owned());
let pool_key = Rc::new(domain.to_string());
self.connector.connect(url)
.map(move |io| {
let (tx, rx) = oneshot::channel();
Expand Down
25 changes: 11 additions & 14 deletions src/client/request.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
use std::fmt;

use Url;

use header::Headers;
use http::{Body, RequestHead};
use method::Method;
use uri::Uri;
use uri::{self, Uri};
use version::HttpVersion;
use std::str::FromStr;

/// A client request to a remote server.
pub struct Request<B = Body> {
method: Method,
url: Url,
uri: Uri,
version: HttpVersion,
headers: Headers,
body: Option<B>,
Expand All @@ -22,20 +19,20 @@ pub struct Request<B = Body> {
impl<B> Request<B> {
/// Construct a new Request.
#[inline]
pub fn new(method: Method, url: Url) -> Request<B> {
pub fn new(method: Method, uri: Uri) -> Request<B> {
Request {
method: method,
url: url,
uri: uri,
version: HttpVersion::default(),
headers: Headers::new(),
body: None,
is_proxy: false,
}
}

/// Read the Request Url.
/// Read the Request Uri.
#[inline]
pub fn url(&self) -> &Url { &self.url }
pub fn uri(&self) -> &Uri { &self.uri }

/// Read the Request Version.
#[inline]
Expand All @@ -57,9 +54,9 @@ impl<B> Request<B> {
#[inline]
pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }

/// Set the `Url` of this request.
/// Set the `Uri` of this request.
#[inline]
pub fn set_url(&mut self, url: Url) { self.url = url; }
pub fn set_uri(&mut self, uri: Uri) { self.uri = uri; }

/// Set the `HttpVersion` of this request.
#[inline]
Expand All @@ -81,7 +78,7 @@ impl<B> fmt::Debug for Request<B> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Request")
.field("method", &self.method)
.field("url", &self.url)
.field("uri", &self.uri)
.field("version", &self.version)
.field("headers", &self.headers)
.finish()
Expand All @@ -90,9 +87,9 @@ impl<B> fmt::Debug for Request<B> {

pub fn split<B>(req: Request<B>) -> (RequestHead, Option<B>) {
let uri = if req.is_proxy {
Uri::from(req.url)
req.uri
} else {
Uri::from_str(&req.url[::url::Position::BeforePath..::url::Position::AfterQuery]).expect("url is not uri")
uri::origin_form(&req.uri)
};
let head = RequestHead {
subject: ::http::RequestLine(req.method, uri),
Expand Down
31 changes: 9 additions & 22 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ use std::str::Utf8Error;
use std::string::FromUtf8Error;

use httparse;
use url;

pub use uri::UriError;

use self::Error::{
Method,
Expand All @@ -21,8 +22,6 @@ use self::Error::{
Utf8
};

pub use url::ParseError;

/// Result type often returned from methods that can have hyper `Error`s.
pub type Result<T> = ::std::result::Result<T, Error>;

Expand All @@ -32,7 +31,7 @@ pub enum Error {
/// An invalid `Method`, such as `GE,T`.
Method,
/// An invalid `Uri`, such as `exam ple.domain`.
Uri(url::ParseError),
Uri(UriError),
/// An invalid `HttpVersion`, such as `HTP/1.1`
Version,
/// An invalid `Header`.
Expand Down Expand Up @@ -102,15 +101,15 @@ impl StdError for Error {
}
}

impl From<IoError> for Error {
fn from(err: IoError) -> Error {
Io(err)
impl From<UriError> for Error {
fn from(err: UriError) -> Error {
Uri(err)
}
}

impl From<url::ParseError> for Error {
fn from(err: url::ParseError) -> Error {
Uri(err)
impl From<IoError> for Error {
fn from(err: IoError) -> Error {
Io(err)
}
}

Expand Down Expand Up @@ -145,7 +144,6 @@ mod tests {
use std::error::Error as StdError;
use std::io;
use httparse;
use url;
use super::Error;
use super::Error::*;

Expand Down Expand Up @@ -185,7 +183,6 @@ mod tests {
fn test_from() {

from_and_cause!(io::Error::new(io::ErrorKind::Other, "other") => Io(..));
from_and_cause!(url::ParseError::EmptyHost => Uri(..));

from!(httparse::Error::HeaderName => Header);
from!(httparse::Error::HeaderName => Header);
Expand All @@ -196,14 +193,4 @@ mod tests {
from!(httparse::Error::TooManyHeaders => TooLarge);
from!(httparse::Error::Version => Version);
}

#[cfg(feature = "openssl")]
#[test]
fn test_from_ssl() {
use openssl::ssl::error::SslError;

from!(SslError::StreamError(
io::Error::new(io::ErrorKind::Other, "ssl negotiation")) => Io(..));
from_and_cause!(SslError::SslSessionClosed => Ssl(..));
}
}
6 changes: 2 additions & 4 deletions src/header/common/content_disposition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@
use language_tags::LanguageTag;
use std::fmt;
use unicase::UniCase;
use url::percent_encoding;

use header::{Header, Raw, parsing};
use header::parsing::{parse_extended_value, HTTP_VALUE};
use header::parsing::{parse_extended_value, http_percent_encode};
use header::shared::Charset;

/// The implied disposition of the content of the HTTP body
Expand Down Expand Up @@ -182,8 +181,7 @@ impl fmt::Display for ContentDisposition {
try!(write!(f, "{}", lang));
};
try!(write!(f, "'"));
try!(f.write_str(
&percent_encoding::percent_encode(bytes, HTTP_VALUE).to_string()))
try!(http_percent_encode(f, bytes))
}
},
DispositionParam::Ext(ref k, ref v) => try!(write!(f, "; {}=\"{}\"", k, v)),
Expand Down
Loading

0 comments on commit 4fb7e6e

Please sign in to comment.