aboutsummaryrefslogtreecommitdiff
path: root/src/origins.rs
blob: 0cc0bc2eb48a6388d1154c7e2612b63f2bcd5158 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use std::str::FromStr;
use url::Url;

#[derive(Clone, Debug)]
pub(crate) struct HttpOrigin {
    pub origin: String,
    pub host_idx: usize,
}

impl HttpOrigin {
    /// Returns the Host header value (e.g. `example.com` for the origin `https://example.com`).
    pub fn host(&self) -> &str {
        &self.origin[self.host_idx..]
    }
}

impl FromStr for HttpOrigin {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let url = Url::parse(s).map_err(|_| "invalid URL")?;
        if url.scheme() != "http" && url.scheme() != "https" {
            return Err("expected http:// or https:// scheme");
        }
        if url.path() != "/" {
            return Err("path must be /");
        }
        Ok(HttpOrigin {
            origin: url.origin().ascii_serialization(),
            host_idx: url.scheme().len() + "://".len(),
        })
    }
}