Router refactoring

This commit is contained in:
Tomasz Drwięga 2016-04-28 10:06:41 +02:00
parent ea4346e945
commit 6a544b7d8e
1 changed files with 14 additions and 33 deletions

View File

@ -22,8 +22,8 @@ use url::{self};
/// HTTP/HTTPS URL type for Iron.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Url {
/// The lower-cased scheme of the URL, typically "http" or "https".
pub scheme: String,
/// Raw url of url
pub raw: url::Url,
/// The host field of the URL, probably a domain.
pub host: Host,
@ -50,18 +50,6 @@ pub struct Url {
/// if a blank password was provided.
/// Otherwise, a non-empty string.
pub password: Option<String>,
/// The URL query string.
///
/// `None` if the `?` character was not part of the input.
/// Otherwise, a possibly empty, percent encoded string.
pub query: Option<String>,
/// The URL fragment.
///
/// `None` if the `#` character was not part of the input.
/// Otherwise, a possibly empty, percent encoded string.
pub fragment: Option<String>
}
impl Url {
@ -82,37 +70,30 @@ impl Url {
/// Create a `Url` from a `rust-url` `Url`.
pub fn from_generic_url(raw_url: url::Url) -> Result<Url, String> {
// Extract the port as a 16-bit unsigned integer.
let port: u16 = match raw_url.port_or_known_default() {
Some(port) => port,
None => {
return Err(format!("Unknown port for scheme: `{}`", raw_url.scheme()))
}
};
// Map empty usernames to None.
let username = match &*raw_url.username() {
let username = match raw_url.username() {
"" => None,
_ => Some(raw_url.username().to_owned())
username => Some(username.to_owned())
};
// Map empty passwords to None.
let password = match raw_url.password() {
None => None,
Some(ref x) if x.is_empty() => None,
Some(password) => Some(password.to_owned())
Some(password) if !password.is_empty() => Some(password.to_owned()),
_ => None,
};
let as_string = |x: &str| x.to_owned();
let port = try!(raw_url.port_or_known_default().ok_or_else(|| format!("Unknown port for scheme: `{}`", raw_url.scheme())));
let host = try!(raw_url.host().ok_or_else(|| "Valid host, because only data:, mailto: protocols does not have host.".to_owned())).to_owned();
let path = try!(raw_url.path_segments().ok_or_else(|| "Valid path segments. In HTTP we won't get cannot-be-a-base URLs".to_owned()))
.map(|part| part.to_owned()).collect();
Ok(Url {
scheme: raw_url.scheme().to_owned(),
host: raw_url.host().expect("Valid host, because only data:, mailto: protocols does not have host.").to_owned(),
port: port,
path: raw_url.path_segments().expect("Valid path segments. In HTTP we won't get cannot-be-a-base URLs").map(&as_string).collect(),
host: host,
path: path,
raw: raw_url,
username: username,
password: password,
query: raw_url.query().map(&as_string),
fragment: raw_url.fragment().map(&as_string),
})
}
}