hyperx/header/common/
host.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::str::FromStr;
4
5use header::{Header, RawLike};
6use header::parsing::from_one_raw_str;
7
8/// The `Host` header.
9///
10/// HTTP/1.1 requires that all requests include a `Host` header, and so hyper
11/// client requests add one automatically.
12///
13/// # Examples
14/// ```
15/// # extern crate http;
16/// use hyperx::header::{Host, TypedHeaders};
17///
18/// let mut headers = http::HeaderMap::new();
19/// headers.encode(
20///     &Host::new("hyper.rs", None)
21/// );
22/// ```
23/// ```
24/// # extern crate http;
25/// use hyperx::header::{Host, TypedHeaders};
26///
27/// let mut headers = http::HeaderMap::new();
28/// headers.encode(
29///     &Host::new("hyper.rs", 8080)
30/// );
31/// ```
32#[derive(Clone, PartialEq, Debug)]
33pub struct Host {
34    hostname: Cow<'static, str>,
35    port: Option<u16>
36}
37
38impl Host {
39    /// Create a `Host` header, providing the hostname and optional port.
40    pub fn new<H, P>(hostname: H, port: P) -> Host
41    where H: Into<Cow<'static, str>>,
42          P: Into<Option<u16>>
43    {
44        Host {
45            hostname: hostname.into(),
46            port: port.into(),
47        }
48    }
49
50    /// Get the hostname, such as example.domain.
51    pub fn hostname(&self) -> &str {
52        self.hostname.as_ref()
53    }
54
55    /// Get the optional port number.
56    pub fn port(&self) -> Option<u16> {
57        self.port
58    }
59}
60
61impl Header for Host {
62    fn header_name() -> &'static str {
63        static NAME: &'static str = "Host";
64        NAME
65    }
66
67    fn parse_header<'a, T>(raw: &'a T) -> ::Result<Host>
68    where T: RawLike<'a>
69    {
70        from_one_raw_str(raw)
71    }
72
73    fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
74        f.fmt_line(self)
75    }
76}
77
78impl fmt::Display for Host {
79    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80        match self.port {
81            None | Some(80) | Some(443) => f.write_str(&self.hostname[..]),
82            Some(port) => write!(f, "{}:{}", self.hostname, port)
83        }
84    }
85}
86
87impl FromStr for Host {
88    type Err = ::Error;
89
90    fn from_str(s: &str) -> ::Result<Host> {
91        let idx = s.rfind(':');
92        let port = idx.and_then(
93            |idx| s[idx + 1..].parse().ok()
94        );
95        let hostname = match port {
96            None => s,
97            Some(_) => &s[..idx.unwrap()]
98        };
99
100        Ok(Host {
101            hostname: hostname.to_owned().into(),
102            port: port,
103        })
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::Host;
110    use header::{Header, Raw};
111
112    #[test]
113    fn test_host() {
114        let r: Raw = vec![b"foo.com".to_vec()].into();
115        let host = Header::parse_header(&r);
116        assert_eq!(host.ok(), Some(Host::new("foo.com", None)));
117
118        let r: Raw = vec![b"foo.com:8080".to_vec()].into();
119        let host = Header::parse_header(&r);
120        assert_eq!(host.ok(), Some(Host::new("foo.com", Some(8080))));
121
122        let r: Raw = vec![b"foo.com".to_vec()].into();
123        let host = Header::parse_header(&r);
124        assert_eq!(host.ok(), Some(Host::new("foo.com", None)));
125
126        let r: Raw = vec![b"[::1]:8080".to_vec()].into();
127        let host = Header::parse_header(&r);
128        assert_eq!(host.ok(), Some(Host::new("[::1]", Some(8080))));
129
130        let r: Raw = vec![b"[::1]".to_vec()].into();
131        let host = Header::parse_header(&r);
132        assert_eq!(host.ok(), Some(Host::new("[::1]", None)));
133    }
134}
135
136bench_header!(bench, Host, { vec![b"foo.com:3000".to_vec()] });
137
138standard_header!(Host, HOST);