1 use std::net::{Ipv4Addr, Ipv6Addr};
2 use url::{ParseError as UrlError, Host};
3 use url::Url;
4 
5 pub trait IntoUrl {
into_url(self) -> Result<Url, UrlError>6     fn into_url(self) -> Result<Url, UrlError>;
7 }
8 
9 impl IntoUrl for Url {
into_url(self) -> Result<Url, UrlError>10     fn into_url(self) -> Result<Url, UrlError> {
11         Ok(self)
12     }
13 }
14 
15 impl<'a> IntoUrl for &'a str {
into_url(self) -> Result<Url, UrlError>16     fn into_url(self) -> Result<Url, UrlError> {
17         Url::parse(self)
18     }
19 }
20 
21 impl<'a> IntoUrl for &'a String {
into_url(self) -> Result<Url, UrlError>22     fn into_url(self) -> Result<Url, UrlError> {
23         Url::parse(self)
24     }
25 }
26 
is_http_scheme(url: &Url) -> bool27 pub fn is_http_scheme(url: &Url) -> bool {
28     url.scheme().starts_with("http")
29 }
30 
is_host_name(host: &str) -> bool31 pub fn is_host_name(host: &str) -> bool {
32     host.parse::<Ipv4Addr>().is_err() && host.parse::<Ipv6Addr>().is_err()
33 }
34 
is_secure(url: &Url) -> bool35 pub fn is_secure(url: &Url) -> bool {
36     if url.scheme() == "https" {
37         return true;
38     }
39     if let Some(u) = url.host() {
40         match u {
41             Host::Domain(d) => d == "localhost",
42             Host::Ipv4(ip) => ip.is_loopback(),
43             Host::Ipv6(ip) => ip.is_loopback(),
44         }
45     } else {
46         false
47     }
48 }
49 
50 #[cfg(test)]
51 pub mod test {
52     use crate::cookie::Cookie;
53     use time::{Duration, OffsetDateTime};
54     use url::Url;
55     #[inline]
url(url: &str) -> Url56     pub fn url(url: &str) -> Url {
57         Url::parse(url).unwrap()
58     }
59     #[inline]
make_cookie<'a>( cookie: &str, url_str: &str, expires: Option<OffsetDateTime>, max_age: Option<u64>, ) -> Cookie<'a>60     pub fn make_cookie<'a>(
61         cookie: &str,
62         url_str: &str,
63         expires: Option<OffsetDateTime>,
64         max_age: Option<u64>,
65     ) -> Cookie<'a> {
66         Cookie::parse(
67             format!(
68                 "{}{}{}",
69                 cookie,
70                 expires.map_or(String::from(""), |e| format!(
71                     "; Expires={}",
72                     e.format("%a, %d %b %Y %H:%M:%S GMT")
73                 )),
74                 max_age.map_or(String::from(""), |m| format!("; Max-Age={}", m))
75             ),
76             &url(url_str),
77         )
78         .unwrap()
79     }
80     #[inline]
in_days(days: i64) -> OffsetDateTime81     pub fn in_days(days: i64) -> OffsetDateTime {
82         OffsetDateTime::now_utc() + Duration::days(days)
83     }
84     #[inline]
in_minutes(mins: i64) -> OffsetDateTime85     pub fn in_minutes(mins: i64) -> OffsetDateTime {
86         OffsetDateTime::now_utc() + Duration::minutes(mins)
87     }
88 }
89