feat(uri): redesign RequestUri type into Uri

Closes #1000

BREAKING CHANGE: The name of `RequestUri` has changed to `Uri`. It is no
  longer an `enum`, but an opaque struct with getter methods.
This commit is contained in:
Guillaume Gomez
2017-01-14 14:38:21 +01:00
committed by Sean McArthur
parent 1868f8548d
commit 9036443e6b
10 changed files with 297 additions and 136 deletions

View File

@@ -23,12 +23,12 @@ impl Service for Echo {
fn call(&self, req: Request) -> Self::Future {
::futures::finished(match (req.method(), req.path()) {
(&Get, Some("/")) | (&Get, Some("/echo")) => {
(&Get, "/") | (&Get, "/echo") => {
Response::new()
.with_header(ContentLength(INDEX.len() as u64))
.with_body(INDEX)
},
(&Post, Some("/echo")) => {
(&Post, "/echo") => {
let mut res = Response::new();
if let Some(len) = req.headers().get::<ContentLength>() {
res.headers_mut().set(len.clone());

View File

@@ -23,7 +23,6 @@ use header::{Headers, Host};
use http::{self, TokioBody};
use method::Method;
use self::pool::{Pool, Pooled};
use uri::RequestUri;
use {Url};
pub use self::connect::{HttpConnector, Connect};
@@ -120,15 +119,10 @@ impl<C: Connect> Service for Client<C> {
fn call(&self, req: Request) -> Self::Future {
let url = req.url().clone();
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.extend(head.headers.iter());
head.subject.1 = RequestUri::AbsolutePath {
path: url.path().to_owned(),
query: url.query().map(ToOwned::to_owned),
};
head.headers = headers;
let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]);

View File

@@ -5,7 +5,7 @@ use Url;
use header::Headers;
use http::{Body, RequestHead};
use method::Method;
use uri::RequestUri;
use uri::Uri;
use version::HttpVersion;
/// A client request to a remote server.
@@ -79,8 +79,9 @@ impl fmt::Debug for Request {
}
pub fn split(req: Request) -> (RequestHead, Option<Body>) {
let uri = Uri::new(&req.url[::url::Position::BeforePath..::url::Position::AfterQuery]).expect("url is uri");
let head = RequestHead {
subject: ::http::RequestLine(req.method, RequestUri::AbsoluteUri(req.url)),
subject: ::http::RequestLine(req.method, uri),
headers: req.headers,
version: req.version,
};

View File

@@ -31,7 +31,7 @@ pub type Result<T> = ::std::result::Result<T, Error>;
pub enum Error {
/// An invalid `Method`, such as `GE,T`.
Method,
/// An invalid `RequestUri`, such as `exam ple.domain`.
/// An invalid `Uri`, such as `exam ple.domain`.
Uri(url::ParseError),
/// An invalid `HttpVersion`, such as `HTP/1.1`
Version,

View File

@@ -574,6 +574,7 @@ mod tests {
use mock::AsyncIo;
use super::{Conn, Writing};
use ::uri::Uri;
#[test]
fn test_conn_init_read() {
@@ -585,10 +586,7 @@ mod tests {
match conn.poll().unwrap() {
Async::Ready(Some(Frame::Message { message, body: false })) => {
assert_eq!(message, MessageHead {
subject: ::http::RequestLine(::Get, ::RequestUri::AbsolutePath {
path: "/".to_string(),
query: None,
}),
subject: ::http::RequestLine(::Get, Uri::new("/").unwrap()),
.. MessageHead::default()
})
},

View File

@@ -6,7 +6,7 @@ use header::{Connection, ConnectionOption};
use header::Headers;
use method::Method;
use status::StatusCode;
use uri::RequestUri;
use uri::Uri;
use version::HttpVersion;
use version::HttpVersion::{Http10, Http11};
@@ -51,7 +51,7 @@ pub struct MessageHead<S> {
pub type RequestHead = MessageHead<RequestLine>;
#[derive(Debug, Default, PartialEq)]
pub struct RequestLine(pub Method, pub RequestUri);
pub struct RequestLine(pub Method, pub Uri);
impl fmt::Display for RequestLine {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {

View File

@@ -41,7 +41,6 @@ pub use http::{Body, Chunk};
pub use method::Method::{self, Get, Head, Post, Delete};
pub use status::StatusCode::{self, Ok, BadRequest, NotFound};
pub use server::Server;
pub use uri::RequestUri;
pub use version::HttpVersion;
macro_rules! unimplemented {

View File

@@ -10,12 +10,12 @@ use version::HttpVersion;
use method::Method;
use header::Headers;
use http::{RequestHead, MessageHead, RequestLine, Body};
use uri::RequestUri;
use uri::Uri;
/// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`.
pub struct Request {
method: Method,
uri: RequestUri,
uri: Uri,
version: HttpVersion,
headers: Headers,
remote_addr: SocketAddr,
@@ -33,7 +33,7 @@ impl Request {
/// The target request-uri for this request.
#[inline]
pub fn uri(&self) -> &RequestUri { &self.uri }
pub fn uri(&self) -> &Uri { &self.uri }
/// The version of HTTP for this request.
#[inline]
@@ -45,22 +45,14 @@ impl Request {
/// The target path of this Request.
#[inline]
pub fn path(&self) -> Option<&str> {
match self.uri {
RequestUri::AbsolutePath { path: ref p, .. } => Some(p.as_str()),
RequestUri::AbsoluteUri(ref url) => Some(url.path()),
_ => None,
}
pub fn path(&self) -> &str {
self.uri.path()
}
/// The query string of this Request.
#[inline]
pub fn query(&self) -> Option<&str> {
match self.uri {
RequestUri::AbsolutePath { query: ref q, .. } => q.as_ref().map(|x| x.as_str()),
RequestUri::AbsoluteUri(ref url) => url.query(),
_ => None,
}
self.uri.query()
}
/// Take the `Body` of this `Request`.
@@ -73,7 +65,7 @@ impl Request {
///
/// Modifying these pieces will have no effect on how hyper behaves.
#[inline]
pub fn deconstruct(self) -> (Method, RequestUri, HttpVersion, Headers, Body) {
pub fn deconstruct(self) -> (Method, Uri, HttpVersion, Headers, Body) {
(self.method, self.uri, self.version, self.headers, self.body)
}
}

View File

@@ -1,7 +1,7 @@
//! HTTP RequestUris
use std::borrow::Cow;
use std::fmt::{Display, self};
use std::str::FromStr;
use url::Url;
use url::{self, Url};
use url::ParseError as UrlError;
use Error;
@@ -21,125 +21,301 @@ use Error;
/// > / authority-form
/// > / asterisk-form
/// > ```
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum RequestUri {
/// The most common request target, an absolute path and optional query.
///
/// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI
/// as `AbsolutePath { path: "/where".to_string(), query: Some("q=now".to_string()) }`.
AbsolutePath {
/// The path part of the request uri.
path: String,
/// The query part of the request uri.
query: Option<String>,
},
/// An absolute URI. Used in conjunction with proxies.
///
/// > When making a request to a proxy, other than a CONNECT or server-wide
/// > OPTIONS request (as detailed below), a client MUST send the target
/// > URI in absolute-form as the request-target.
///
/// An example StartLine with an `AbsoluteUri` would be
/// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`.
AbsoluteUri(Url),
/// The authority form is only for use with `CONNECT` requests.
///
/// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`.
Authority(String),
/// The star is used to target the entire server, instead of a specific resource.
///
/// This is only used for a server-wide `OPTIONS` request.
Star,
///
/// # Uri explanations
///
/// abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
/// |-| |-------------------------------||--------| |-------------------| |-----|
/// | | | | |
/// scheme authority path query fragment
#[derive(Clone)]
pub struct Uri {
source: Cow<'static, str>,
scheme_end: Option<usize>,
authority_end: Option<usize>,
query: Option<usize>,
fragment: Option<usize>,
}
impl Default for RequestUri {
fn default() -> RequestUri {
RequestUri::Star
}
}
impl FromStr for RequestUri {
type Err = Error;
fn from_str(s: &str) -> Result<RequestUri, Error> {
impl Uri {
/// Parse a string into a `Uri`.
pub fn new(s: &str) -> Result<Uri, Error> {
let bytes = s.as_bytes();
if bytes.len() == 0 {
Err(Error::Uri(UrlError::RelativeUrlWithoutBase))
} else if bytes == b"*" {
Ok(RequestUri::Star)
Ok(Uri {
source: "*".into(),
scheme_end: None,
authority_end: None,
query: None,
fragment: None,
})
} else if bytes == b"/" {
Ok(Uri::default())
} else if bytes.starts_with(b"/") {
let mut temp = "http://example.com".to_owned();
temp.push_str(s);
let url = try!(Url::parse(&temp));
Ok(RequestUri::AbsolutePath {
path: url.path().to_owned(),
query: url.query().map(|q| q.to_owned()),
let query_len = url.query().unwrap_or("").len();
let fragment_len = url.fragment().unwrap_or("").len();
Ok(Uri {
source: s.to_owned().into(),
scheme_end: None,
authority_end: None,
query: if query_len > 0 { Some(query_len) } else { None },
fragment: if fragment_len > 0 { Some(fragment_len) } else { None },
})
} else if bytes.contains(&b'/') {
Ok(RequestUri::AbsoluteUri(try!(Url::parse(s))))
} else {
let mut temp = "http://".to_owned();
temp.push_str(s);
let url = try!(Url::parse(&temp));
if url.query().is_some() {
return Err(Error::Uri(UrlError::RelativeUrlWithoutBase));
}
//TODO: compare vs u.authority()?
Ok(RequestUri::Authority(s.to_owned()))
}
}
}
impl Display for RequestUri {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RequestUri::AbsolutePath { ref path, ref query } => {
try!(f.write_str(path));
match *query {
Some(ref q) => write!(f, "?{}", q),
None => Ok(()),
} else if s.contains("://") {
let url = try!(Url::parse(s));
let query_len = url.query().unwrap_or("").len();
let v: Vec<&str> = s.split("://").collect();
let authority_end = v.last().unwrap()
.split(url.path())
.next()
.unwrap_or(s)
.len() + if v.len() == 2 { v[0].len() + 3 } else { 0 };
let fragment_len = url.fragment().unwrap_or("").len();
match url.origin() {
url::Origin::Opaque(_) => Err(Error::Method),
url::Origin::Tuple(scheme, _, _) => {
Ok(Uri {
source: url.to_string().into(),
scheme_end: Some(scheme.len()),
authority_end: if authority_end > 0 { Some(authority_end) } else { None },
query: if query_len > 0 { Some(query_len) } else { None },
fragment: if fragment_len > 0 { Some(fragment_len) } else { None },
})
}
}
RequestUri::AbsoluteUri(ref url) => write!(f, "{}", url),
RequestUri::Authority(ref path) => f.write_str(path),
RequestUri::Star => f.write_str("*")
} else {
Ok(Uri {
source: s.to_owned().into(),
scheme_end: None,
authority_end: Some(s.len()),
query: None,
fragment: None,
})
}
}
/// Get the path of this `Uri`.
pub fn path(&self) -> &str {
let index = self.authority_end.unwrap_or(self.scheme_end.unwrap_or(0));
let query_len = self.query.unwrap_or(0);
let fragment_len = self.fragment.unwrap_or(0);
let end = self.source.len() - if query_len > 0 { query_len + 1 } else { 0 } -
if fragment_len > 0 { fragment_len + 1 } else { 0 };
if index >= end {
""
} else {
&self.source[index..end]
}
}
/// Get the scheme of this `Uri`.
pub fn scheme(&self) -> Option<&str> {
if let Some(end) = self.scheme_end {
Some(&self.source[..end])
} else {
None
}
}
/// Get the authority of this `Uri`.
pub fn authority(&self) -> Option<&str> {
if let Some(end) = self.authority_end {
let index = self.scheme_end.map(|i| i + 3).unwrap_or(0);
Some(&self.source[index..end])
} else {
None
}
}
/// Get the host of this `Uri`.
pub fn host(&self) -> Option<&str> {
if let Some(auth) = self.authority() {
auth.split(":").next()
} else {
None
}
}
/// Get the port of this `Uri.
pub fn port(&self) -> Option<u16> {
if let Some(auth) = self.authority() {
let v: Vec<&str> = auth.split(":").collect();
if v.len() == 2 {
u16::from_str(v[1]).ok()
} else {
None
}
} else {
None
}
}
/// Get the query string of this `Uri`, starting after the `?`.
pub fn query(&self) -> Option<&str> {
let fragment_len = self.fragment.unwrap_or(0);
let fragment_len = if fragment_len > 0 { fragment_len + 1 } else { 0 };
if let Some(len) = self.query {
Some(&self.source[self.source.len() - len - fragment_len..self.source.len() - fragment_len])
} else {
None
}
}
#[cfg(test)]
fn fragment(&self) -> Option<&str> {
if let Some(len) = self.fragment {
Some(&self.source[self.source.len() - len..])
} else {
None
}
}
}
#[test]
fn test_uri_fromstr() {
fn parse(s: &str, result: RequestUri) {
assert_eq!(s.parse::<RequestUri>().unwrap(), result);
}
fn parse_err(s: &str) {
assert!(s.parse::<RequestUri>().is_err());
}
impl FromStr for Uri {
type Err = Error;
parse("*", RequestUri::Star);
parse("**", RequestUri::Authority("**".to_owned()));
parse("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()));
parse("hyper.rs", RequestUri::Authority("hyper.rs".to_owned()));
parse_err("hyper.rs?key=value");
parse_err("hyper.rs/");
parse("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None });
fn from_str(s: &str) -> Result<Uri, Error> {
Uri::new(s)
}
}
impl From<Url> for Uri {
fn from(url: Url) -> Uri {
Uri::new(url.as_str()).expect("Uri::From<Url> failed")
}
}
impl PartialEq for Uri {
fn eq(&self, other: &Uri) -> bool {
self.source == other.source
}
}
impl AsRef<str> for Uri {
fn as_ref(&self) -> &str {
&self.source
}
}
impl Default for Uri {
fn default() -> Uri {
Uri {
source: "/".into(),
scheme_end: None,
authority_end: None,
query: None,
fragment: None,
}
}
}
impl fmt::Debug for Uri {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.source.as_ref(), f)
}
}
impl Display for Uri {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.source)
}
}
macro_rules! test_parse {
(
$test_name:ident,
$str:expr,
$($method:ident = $value:expr,)*
) => (
#[test]
fn $test_name() {
let uri = Uri::new($str).unwrap();
$(
assert_eq!(uri.$method(), $value);
)+
}
);
}
test_parse! {
test_uri_parse_origin_form,
"/some/path/here?and=then&hello#and-bye",
scheme = None,
authority = None,
path = "/some/path/here",
query = Some("and=then&hello"),
fragment = Some("and-bye"),
}
test_parse! {
test_uri_parse_absolute_form,
"http://127.0.0.1:61761/chunks",
scheme = Some("http"),
authority = Some("127.0.0.1:61761"),
path = "/chunks",
query = None,
fragment = None,
}
test_parse! {
test_uri_parse_absolute_form_without_path,
"https://127.0.0.1:61761",
scheme = Some("https"),
authority = Some("127.0.0.1:61761"),
path = "/",
query = None,
fragment = None,
}
test_parse! {
test_uri_parse_asterisk_form,
"*",
scheme = None,
authority = None,
path = "*",
query = None,
fragment = None,
}
test_parse! {
test_uri_parse_authority_form,
"localhost:3000",
scheme = None,
authority = Some("localhost:3000"),
path = "",
query = None,
fragment = None,
}
#[test]
fn test_uri_display() {
fn assert_display(expected_string: &str, request_uri: RequestUri) {
assert_eq!(expected_string, format!("{}", request_uri));
fn test_uri_parse_error() {
fn err(s: &str) {
Uri::new(s).unwrap_err();
}
assert_display("*", RequestUri::Star);
assert_display("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()));
assert_display("hyper.rs", RequestUri::Authority("hyper.rs".to_owned()));
assert_display("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None });
assert_display("/where?key=value", RequestUri::AbsolutePath {
path: "/where".to_owned(),
query: Some("key=value".to_owned()),
});
err("http://");
//TODO: these should error
//err("htt:p//host");
//err("hyper.rs/");
//err("hyper.rs?key=val");
}
#[test]
fn test_uri_from_url() {
let uri = Uri::from(Url::parse("http://test.com/nazghul?test=3").unwrap());
assert_eq!(uri.path(), "/nazghul");
assert_eq!(uri.authority(), Some("test.com"));
assert_eq!(uri.scheme(), Some("http"));
assert_eq!(uri.query(), Some("test=3"));
assert_eq!(uri.as_ref(), "http://test.com/nazghul?test=3");
}

View File

@@ -47,6 +47,7 @@ macro_rules! test {
fn $name() {
#![allow(unused)]
use hyper::header::*;
let _ = pretty_env_logger::init();
let server = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = server.local_addr().unwrap();
let mut core = Core::new().unwrap();
@@ -74,7 +75,7 @@ macro_rules! test {
while n < buf.len() && n < expected.len() {
n += inc.read(&mut buf[n..]).unwrap();
}
assert_eq!(s(&buf[..n]), expected);
assert_eq!(s(&buf[..n]), expected, "expected is invalid");
inc.write_all($server_reply.as_ref()).unwrap();
tx.complete(());
@@ -85,9 +86,9 @@ macro_rules! test {
let work = res.join(rx).map(|r| r.0);
let res = core.run(work).unwrap();
assert_eq!(res.status(), &StatusCode::$client_status);
assert_eq!(res.status(), &StatusCode::$client_status, "status is invalid");
$(
assert_eq!(res.headers().get(), Some(&$response_headers));
assert_eq!(res.headers().get(), Some(&$response_headers), "headers are invalid");
)*
}
);