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:
committed by
Sean McArthur
parent
1868f8548d
commit
9036443e6b
@@ -23,12 +23,12 @@ impl Service for Echo {
|
|||||||
|
|
||||||
fn call(&self, req: Request) -> Self::Future {
|
fn call(&self, req: Request) -> Self::Future {
|
||||||
::futures::finished(match (req.method(), req.path()) {
|
::futures::finished(match (req.method(), req.path()) {
|
||||||
(&Get, Some("/")) | (&Get, Some("/echo")) => {
|
(&Get, "/") | (&Get, "/echo") => {
|
||||||
Response::new()
|
Response::new()
|
||||||
.with_header(ContentLength(INDEX.len() as u64))
|
.with_header(ContentLength(INDEX.len() as u64))
|
||||||
.with_body(INDEX)
|
.with_body(INDEX)
|
||||||
},
|
},
|
||||||
(&Post, Some("/echo")) => {
|
(&Post, "/echo") => {
|
||||||
let mut res = Response::new();
|
let mut res = Response::new();
|
||||||
if let Some(len) = req.headers().get::<ContentLength>() {
|
if let Some(len) = req.headers().get::<ContentLength>() {
|
||||||
res.headers_mut().set(len.clone());
|
res.headers_mut().set(len.clone());
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ use header::{Headers, Host};
|
|||||||
use http::{self, TokioBody};
|
use http::{self, TokioBody};
|
||||||
use method::Method;
|
use method::Method;
|
||||||
use self::pool::{Pool, Pooled};
|
use self::pool::{Pool, Pooled};
|
||||||
use uri::RequestUri;
|
|
||||||
use {Url};
|
use {Url};
|
||||||
|
|
||||||
pub use self::connect::{HttpConnector, Connect};
|
pub use self::connect::{HttpConnector, Connect};
|
||||||
@@ -120,15 +119,10 @@ impl<C: Connect> Service for Client<C> {
|
|||||||
|
|
||||||
fn call(&self, req: Request) -> Self::Future {
|
fn call(&self, req: Request) -> Self::Future {
|
||||||
let url = req.url().clone();
|
let url = req.url().clone();
|
||||||
|
|
||||||
let (mut head, body) = request::split(req);
|
let (mut head, body) = request::split(req);
|
||||||
let mut headers = Headers::new();
|
let mut headers = Headers::new();
|
||||||
headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port()));
|
headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port()));
|
||||||
headers.extend(head.headers.iter());
|
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;
|
head.headers = headers;
|
||||||
|
|
||||||
let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]);
|
let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use Url;
|
|||||||
use header::Headers;
|
use header::Headers;
|
||||||
use http::{Body, RequestHead};
|
use http::{Body, RequestHead};
|
||||||
use method::Method;
|
use method::Method;
|
||||||
use uri::RequestUri;
|
use uri::Uri;
|
||||||
use version::HttpVersion;
|
use version::HttpVersion;
|
||||||
|
|
||||||
/// A client request to a remote server.
|
/// A client request to a remote server.
|
||||||
@@ -79,8 +79,9 @@ impl fmt::Debug for Request {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn split(req: Request) -> (RequestHead, Option<Body>) {
|
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 {
|
let head = RequestHead {
|
||||||
subject: ::http::RequestLine(req.method, RequestUri::AbsoluteUri(req.url)),
|
subject: ::http::RequestLine(req.method, uri),
|
||||||
headers: req.headers,
|
headers: req.headers,
|
||||||
version: req.version,
|
version: req.version,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ pub type Result<T> = ::std::result::Result<T, Error>;
|
|||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// An invalid `Method`, such as `GE,T`.
|
/// An invalid `Method`, such as `GE,T`.
|
||||||
Method,
|
Method,
|
||||||
/// An invalid `RequestUri`, such as `exam ple.domain`.
|
/// An invalid `Uri`, such as `exam ple.domain`.
|
||||||
Uri(url::ParseError),
|
Uri(url::ParseError),
|
||||||
/// An invalid `HttpVersion`, such as `HTP/1.1`
|
/// An invalid `HttpVersion`, such as `HTP/1.1`
|
||||||
Version,
|
Version,
|
||||||
|
|||||||
@@ -574,6 +574,7 @@ mod tests {
|
|||||||
use mock::AsyncIo;
|
use mock::AsyncIo;
|
||||||
|
|
||||||
use super::{Conn, Writing};
|
use super::{Conn, Writing};
|
||||||
|
use ::uri::Uri;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_conn_init_read() {
|
fn test_conn_init_read() {
|
||||||
@@ -585,10 +586,7 @@ mod tests {
|
|||||||
match conn.poll().unwrap() {
|
match conn.poll().unwrap() {
|
||||||
Async::Ready(Some(Frame::Message { message, body: false })) => {
|
Async::Ready(Some(Frame::Message { message, body: false })) => {
|
||||||
assert_eq!(message, MessageHead {
|
assert_eq!(message, MessageHead {
|
||||||
subject: ::http::RequestLine(::Get, ::RequestUri::AbsolutePath {
|
subject: ::http::RequestLine(::Get, Uri::new("/").unwrap()),
|
||||||
path: "/".to_string(),
|
|
||||||
query: None,
|
|
||||||
}),
|
|
||||||
.. MessageHead::default()
|
.. MessageHead::default()
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use header::{Connection, ConnectionOption};
|
|||||||
use header::Headers;
|
use header::Headers;
|
||||||
use method::Method;
|
use method::Method;
|
||||||
use status::StatusCode;
|
use status::StatusCode;
|
||||||
use uri::RequestUri;
|
use uri::Uri;
|
||||||
use version::HttpVersion;
|
use version::HttpVersion;
|
||||||
use version::HttpVersion::{Http10, Http11};
|
use version::HttpVersion::{Http10, Http11};
|
||||||
|
|
||||||
@@ -51,7 +51,7 @@ pub struct MessageHead<S> {
|
|||||||
pub type RequestHead = MessageHead<RequestLine>;
|
pub type RequestHead = MessageHead<RequestLine>;
|
||||||
|
|
||||||
#[derive(Debug, Default, PartialEq)]
|
#[derive(Debug, Default, PartialEq)]
|
||||||
pub struct RequestLine(pub Method, pub RequestUri);
|
pub struct RequestLine(pub Method, pub Uri);
|
||||||
|
|
||||||
impl fmt::Display for RequestLine {
|
impl fmt::Display for RequestLine {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ pub use http::{Body, Chunk};
|
|||||||
pub use method::Method::{self, Get, Head, Post, Delete};
|
pub use method::Method::{self, Get, Head, Post, Delete};
|
||||||
pub use status::StatusCode::{self, Ok, BadRequest, NotFound};
|
pub use status::StatusCode::{self, Ok, BadRequest, NotFound};
|
||||||
pub use server::Server;
|
pub use server::Server;
|
||||||
pub use uri::RequestUri;
|
|
||||||
pub use version::HttpVersion;
|
pub use version::HttpVersion;
|
||||||
|
|
||||||
macro_rules! unimplemented {
|
macro_rules! unimplemented {
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ use version::HttpVersion;
|
|||||||
use method::Method;
|
use method::Method;
|
||||||
use header::Headers;
|
use header::Headers;
|
||||||
use http::{RequestHead, MessageHead, RequestLine, Body};
|
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`.
|
/// A request bundles several parts of an incoming `NetworkStream`, given to a `Handler`.
|
||||||
pub struct Request {
|
pub struct Request {
|
||||||
method: Method,
|
method: Method,
|
||||||
uri: RequestUri,
|
uri: Uri,
|
||||||
version: HttpVersion,
|
version: HttpVersion,
|
||||||
headers: Headers,
|
headers: Headers,
|
||||||
remote_addr: SocketAddr,
|
remote_addr: SocketAddr,
|
||||||
@@ -33,7 +33,7 @@ impl Request {
|
|||||||
|
|
||||||
/// The target request-uri for this request.
|
/// The target request-uri for this request.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn uri(&self) -> &RequestUri { &self.uri }
|
pub fn uri(&self) -> &Uri { &self.uri }
|
||||||
|
|
||||||
/// The version of HTTP for this request.
|
/// The version of HTTP for this request.
|
||||||
#[inline]
|
#[inline]
|
||||||
@@ -45,22 +45,14 @@ impl Request {
|
|||||||
|
|
||||||
/// The target path of this Request.
|
/// The target path of this Request.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn path(&self) -> Option<&str> {
|
pub fn path(&self) -> &str {
|
||||||
match self.uri {
|
self.uri.path()
|
||||||
RequestUri::AbsolutePath { path: ref p, .. } => Some(p.as_str()),
|
|
||||||
RequestUri::AbsoluteUri(ref url) => Some(url.path()),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The query string of this Request.
|
/// The query string of this Request.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn query(&self) -> Option<&str> {
|
pub fn query(&self) -> Option<&str> {
|
||||||
match self.uri {
|
self.uri.query()
|
||||||
RequestUri::AbsolutePath { query: ref q, .. } => q.as_ref().map(|x| x.as_str()),
|
|
||||||
RequestUri::AbsoluteUri(ref url) => url.query(),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Take the `Body` of this `Request`.
|
/// Take the `Body` of this `Request`.
|
||||||
@@ -73,7 +65,7 @@ impl Request {
|
|||||||
///
|
///
|
||||||
/// Modifying these pieces will have no effect on how hyper behaves.
|
/// Modifying these pieces will have no effect on how hyper behaves.
|
||||||
#[inline]
|
#[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)
|
(self.method, self.uri, self.version, self.headers, self.body)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
358
src/uri.rs
358
src/uri.rs
@@ -1,7 +1,7 @@
|
|||||||
//! HTTP RequestUris
|
use std::borrow::Cow;
|
||||||
use std::fmt::{Display, self};
|
use std::fmt::{Display, self};
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use url::Url;
|
use url::{self, Url};
|
||||||
use url::ParseError as UrlError;
|
use url::ParseError as UrlError;
|
||||||
|
|
||||||
use Error;
|
use Error;
|
||||||
@@ -21,125 +21,301 @@ use Error;
|
|||||||
/// > / authority-form
|
/// > / authority-form
|
||||||
/// > / asterisk-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
|
/// # Uri explanations
|
||||||
/// 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
|
/// abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1
|
||||||
/// > OPTIONS request (as detailed below), a client MUST send the target
|
/// |-| |-------------------------------||--------| |-------------------| |-----|
|
||||||
/// > URI in absolute-form as the request-target.
|
/// | | | | |
|
||||||
///
|
/// scheme authority path query fragment
|
||||||
/// An example StartLine with an `AbsoluteUri` would be
|
#[derive(Clone)]
|
||||||
/// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`.
|
pub struct Uri {
|
||||||
AbsoluteUri(Url),
|
source: Cow<'static, str>,
|
||||||
|
scheme_end: Option<usize>,
|
||||||
/// The authority form is only for use with `CONNECT` requests.
|
authority_end: Option<usize>,
|
||||||
///
|
query: Option<usize>,
|
||||||
/// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`.
|
fragment: Option<usize>,
|
||||||
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,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for RequestUri {
|
impl Uri {
|
||||||
fn default() -> RequestUri {
|
/// Parse a string into a `Uri`.
|
||||||
RequestUri::Star
|
pub fn new(s: &str) -> Result<Uri, Error> {
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromStr for RequestUri {
|
|
||||||
type Err = Error;
|
|
||||||
|
|
||||||
fn from_str(s: &str) -> Result<RequestUri, Error> {
|
|
||||||
let bytes = s.as_bytes();
|
let bytes = s.as_bytes();
|
||||||
if bytes.len() == 0 {
|
if bytes.len() == 0 {
|
||||||
Err(Error::Uri(UrlError::RelativeUrlWithoutBase))
|
Err(Error::Uri(UrlError::RelativeUrlWithoutBase))
|
||||||
} else if bytes == b"*" {
|
} 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"/") {
|
} else if bytes.starts_with(b"/") {
|
||||||
let mut temp = "http://example.com".to_owned();
|
let mut temp = "http://example.com".to_owned();
|
||||||
temp.push_str(s);
|
temp.push_str(s);
|
||||||
let url = try!(Url::parse(&temp));
|
let url = try!(Url::parse(&temp));
|
||||||
Ok(RequestUri::AbsolutePath {
|
let query_len = url.query().unwrap_or("").len();
|
||||||
path: url.path().to_owned(),
|
let fragment_len = url.fragment().unwrap_or("").len();
|
||||||
query: url.query().map(|q| q.to_owned()),
|
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'/') {
|
} else if s.contains("://") {
|
||||||
Ok(RequestUri::AbsoluteUri(try!(Url::parse(s))))
|
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 },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
let mut temp = "http://".to_owned();
|
Ok(Uri {
|
||||||
temp.push_str(s);
|
source: s.to_owned().into(),
|
||||||
let url = try!(Url::parse(&temp));
|
scheme_end: None,
|
||||||
if url.query().is_some() {
|
authority_end: Some(s.len()),
|
||||||
return Err(Error::Uri(UrlError::RelativeUrlWithoutBase));
|
query: None,
|
||||||
|
fragment: None,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
//TODO: compare vs u.authority()?
|
}
|
||||||
Ok(RequestUri::Authority(s.to_owned()))
|
|
||||||
|
/// 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for RequestUri {
|
impl FromStr for Uri {
|
||||||
|
type Err = Error;
|
||||||
|
|
||||||
|
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 {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
match *self {
|
fmt::Debug::fmt(&self.source.as_ref(), f)
|
||||||
RequestUri::AbsolutePath { ref path, ref query } => {
|
|
||||||
try!(f.write_str(path));
|
|
||||||
match *query {
|
|
||||||
Some(ref q) => write!(f, "?{}", q),
|
|
||||||
None => Ok(()),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RequestUri::AbsoluteUri(ref url) => write!(f, "{}", url),
|
|
||||||
RequestUri::Authority(ref path) => f.write_str(path),
|
impl Display for Uri {
|
||||||
RequestUri::Star => f.write_str("*")
|
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]
|
#[test]
|
||||||
fn test_uri_fromstr() {
|
fn test_uri_parse_error() {
|
||||||
fn parse(s: &str, result: RequestUri) {
|
fn err(s: &str) {
|
||||||
assert_eq!(s.parse::<RequestUri>().unwrap(), result);
|
Uri::new(s).unwrap_err();
|
||||||
}
|
|
||||||
fn parse_err(s: &str) {
|
|
||||||
assert!(s.parse::<RequestUri>().is_err());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
parse("*", RequestUri::Star);
|
err("http://");
|
||||||
parse("**", RequestUri::Authority("**".to_owned()));
|
//TODO: these should error
|
||||||
parse("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()));
|
//err("htt:p//host");
|
||||||
parse("hyper.rs", RequestUri::Authority("hyper.rs".to_owned()));
|
//err("hyper.rs/");
|
||||||
parse_err("hyper.rs?key=value");
|
//err("hyper.rs?key=val");
|
||||||
parse_err("hyper.rs/");
|
|
||||||
parse("/", RequestUri::AbsolutePath { path: "/".to_owned(), query: None });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_uri_display() {
|
fn test_uri_from_url() {
|
||||||
fn assert_display(expected_string: &str, request_uri: RequestUri) {
|
let uri = Uri::from(Url::parse("http://test.com/nazghul?test=3").unwrap());
|
||||||
assert_eq!(expected_string, format!("{}", request_uri));
|
assert_eq!(uri.path(), "/nazghul");
|
||||||
}
|
assert_eq!(uri.authority(), Some("test.com"));
|
||||||
|
assert_eq!(uri.scheme(), Some("http"));
|
||||||
assert_display("*", RequestUri::Star);
|
assert_eq!(uri.query(), Some("test=3"));
|
||||||
assert_display("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()));
|
assert_eq!(uri.as_ref(), "http://test.com/nazghul?test=3");
|
||||||
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()),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ macro_rules! test {
|
|||||||
fn $name() {
|
fn $name() {
|
||||||
#![allow(unused)]
|
#![allow(unused)]
|
||||||
use hyper::header::*;
|
use hyper::header::*;
|
||||||
|
let _ = pretty_env_logger::init();
|
||||||
let server = TcpListener::bind("127.0.0.1:0").unwrap();
|
let server = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
let addr = server.local_addr().unwrap();
|
let addr = server.local_addr().unwrap();
|
||||||
let mut core = Core::new().unwrap();
|
let mut core = Core::new().unwrap();
|
||||||
@@ -74,7 +75,7 @@ macro_rules! test {
|
|||||||
while n < buf.len() && n < expected.len() {
|
while n < buf.len() && n < expected.len() {
|
||||||
n += inc.read(&mut buf[n..]).unwrap();
|
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();
|
inc.write_all($server_reply.as_ref()).unwrap();
|
||||||
tx.complete(());
|
tx.complete(());
|
||||||
@@ -85,9 +86,9 @@ macro_rules! test {
|
|||||||
let work = res.join(rx).map(|r| r.0);
|
let work = res.join(rx).map(|r| r.0);
|
||||||
|
|
||||||
let res = core.run(work).unwrap();
|
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");
|
||||||
)*
|
)*
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user