hyper_sync/
uri.rs

1//! HTTP RequestUris
2use std::fmt::{Display, self};
3use std::str::FromStr;
4use url::Url;
5use url::ParseError as UrlError;
6
7use Error;
8
9/// The Request-URI of a Request's StartLine.
10///
11/// From Section 5.3, Request Target:
12/// > Once an inbound connection is obtained, the client sends an HTTP
13/// > request message (Section 3) with a request-target derived from the
14/// > target URI.  There are four distinct formats for the request-target,
15/// > depending on both the method being requested and whether the request
16/// > is to a proxy.
17/// >
18/// > ```notrust
19/// > request-target = origin-form
20/// >                / absolute-form
21/// >                / authority-form
22/// >                / asterisk-form
23/// > ```
24#[derive(Debug, PartialEq, Clone)]
25pub enum RequestUri {
26    /// The most common request target, an absolute path and optional query.
27    ///
28    /// For example, the line `GET /where?q=now HTTP/1.1` would parse the URI
29    /// as `AbsolutePath("/where?q=now".to_string())`.
30    AbsolutePath(String),
31
32    /// An absolute URI. Used in conjunction with proxies.
33    ///
34    /// > When making a request to a proxy, other than a CONNECT or server-wide
35    /// > OPTIONS request (as detailed below), a client MUST send the target
36    /// > URI in absolute-form as the request-target.
37    ///
38    /// An example StartLine with an `AbsoluteUri` would be
39    /// `GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1`.
40    AbsoluteUri(Url),
41
42    /// The authority form is only for use with `CONNECT` requests.
43    ///
44    /// An example StartLine: `CONNECT www.example.com:80 HTTP/1.1`.
45    Authority(String),
46
47    /// The star is used to target the entire server, instead of a specific resource.
48    ///
49    /// This is only used for a server-wide `OPTIONS` request.
50    Star,
51}
52
53impl FromStr for RequestUri {
54    type Err = Error;
55
56    fn from_str(s: &str) -> Result<RequestUri, Error> {
57        let bytes = s.as_bytes();
58        if bytes.is_empty() {
59            Err(Error::Uri(UrlError::RelativeUrlWithoutBase))
60        } else if bytes == b"*" {
61            Ok(RequestUri::Star)
62        } else if bytes.starts_with(b"/") {
63            Ok(RequestUri::AbsolutePath(s.to_owned()))
64        } else if bytes.contains(&b'/') {
65            Ok(RequestUri::AbsoluteUri(try!(Url::parse(s))))
66        } else {
67            let mut temp = "http://".to_owned();
68            temp.push_str(s);
69            try!(Url::parse(&temp[..]));
70            todo!("compare vs u.authority()");
71            Ok(RequestUri::Authority(s.to_owned()))
72        }
73    }
74}
75
76impl Display for RequestUri {
77    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78        match *self {
79            RequestUri::AbsolutePath(ref path) => f.write_str(path),
80            RequestUri::AbsoluteUri(ref url) => write!(f, "{}", url),
81            RequestUri::Authority(ref path) => f.write_str(path),
82            RequestUri::Star => f.write_str("*")
83        }
84    }
85}
86
87#[test]
88fn test_uri_fromstr() {
89    fn read(s: &str, result: RequestUri) {
90        assert_eq!(s.parse::<RequestUri>().unwrap(), result);
91    }
92
93    read("*", RequestUri::Star);
94    read("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()));
95    read("hyper.rs", RequestUri::Authority("hyper.rs".to_owned()));
96    read("/", RequestUri::AbsolutePath("/".to_owned()));
97}
98
99#[test]
100fn test_uri_display() {
101    fn assert_display(expected_string: &str, request_uri: RequestUri) {
102        assert_eq!(expected_string, format!("{}", request_uri));
103    }
104
105    assert_display("*", RequestUri::Star);
106    assert_display("http://hyper.rs/", RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()));
107    assert_display("hyper.rs", RequestUri::Authority("hyper.rs".to_owned()));
108    assert_display("/", RequestUri::AbsolutePath("/".to_owned()));
109
110}