hyper_sync/header/common/
access_control_allow_origin.rs

1use std::fmt::{self, Display};
2use std::str;
3
4use header::{Header, Raw};
5
6/// The `Access-Control-Allow-Origin` response header,
7/// part of [CORS](http://www.w3.org/TR/cors/#access-control-allow-origin-response-header)
8///
9/// The `Access-Control-Allow-Origin` header indicates whether a resource
10/// can be shared based by returning the value of the Origin request header,
11/// `*`, or `null` in the response.
12///
13/// # ABNF
14///
15/// ```text
16/// Access-Control-Allow-Origin = "Access-Control-Allow-Origin" ":" origin-list-or-null | "*"
17/// ```
18///
19/// # Example values
20/// * `null`
21/// * `*`
22/// * `http://google.com/`
23///
24/// # Examples
25/// ```
26/// use hyper_sync::header::{Headers, AccessControlAllowOrigin};
27///
28/// let mut headers = Headers::new();
29/// headers.set(
30///     AccessControlAllowOrigin::Any
31/// );
32/// ```
33/// ```
34/// use hyper_sync::header::{Headers, AccessControlAllowOrigin};
35///
36/// let mut headers = Headers::new();
37/// headers.set(
38///     AccessControlAllowOrigin::Null,
39/// );
40/// ```
41/// ```
42/// use hyper_sync::header::{Headers, AccessControlAllowOrigin};
43///
44/// let mut headers = Headers::new();
45/// headers.set(
46///     AccessControlAllowOrigin::Value("http://hyper.rs".to_owned())
47/// );
48/// ```
49#[derive(Clone, PartialEq, Debug)]
50pub enum AccessControlAllowOrigin {
51    /// Allow all origins
52    Any,
53    /// A hidden origin
54    Null,
55    /// Allow one particular origin
56    Value(String),
57}
58
59impl Header for AccessControlAllowOrigin {
60    fn header_name() -> &'static str {
61        static NAME: &'static str = "Access-Control-Allow-Origin";
62        NAME
63    }
64
65    fn parse_header(raw: &Raw) -> ::Result<AccessControlAllowOrigin> {
66        if let Some(line) = raw.one() {
67            Ok(match line {
68                b"*" => AccessControlAllowOrigin::Any,
69                b"null" => AccessControlAllowOrigin::Null,
70                _ => AccessControlAllowOrigin::Value(try!(str::from_utf8(line)).into())
71            })
72        } else {
73            Err(::Error::Header)
74        }
75    }
76
77    fn fmt_header(&self, f: &mut ::header::Formatter) -> fmt::Result {
78        f.fmt_line(self)
79    }
80}
81
82impl Display for AccessControlAllowOrigin {
83    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
84        match *self {
85            AccessControlAllowOrigin::Any => f.write_str("*"),
86            AccessControlAllowOrigin::Null => f.write_str("null"),
87            AccessControlAllowOrigin::Value(ref url) => Display::fmt(url, f),
88        }
89    }
90}
91
92#[cfg(test)]
93mod test_access_control_allow_origin {
94    use header::*;
95    use super::AccessControlAllowOrigin as HeaderField;
96    test_header!(test1, vec![b"null"]);
97    test_header!(test2, vec![b"*"]);
98    test_header!(test3, vec![b"http://google.com/"]);
99}