plane_common/
controller_address.rs

1use url::Url;
2
3/// An authorized address combines a URL with an optional bearer token.
4#[derive(Clone, Debug)]
5pub struct AuthorizedAddress {
6    pub url: Url,
7    pub bearer_token: Option<String>,
8}
9
10impl AuthorizedAddress {
11    pub fn join(&self, path: &str) -> AuthorizedAddress {
12        let url = self.url.clone();
13        let url = url.join(path).expect("URL is always valid");
14
15        Self {
16            url,
17            bearer_token: self.bearer_token.clone(),
18        }
19    }
20
21    pub fn to_websocket_address(mut self) -> AuthorizedAddress {
22        if self.url.scheme() == "http" {
23            self.url
24                .set_scheme("ws")
25                .expect("should always be able to set URL scheme to static value ws");
26        } else if self.url.scheme() == "https" {
27            self.url
28                .set_scheme("wss")
29                .expect("should always be able to set URL scheme to static value wss");
30        }
31
32        self
33    }
34
35    pub fn bearer_header(&self) -> Option<String> {
36        self.bearer_token
37            .as_ref()
38            .map(|token| format!("Bearer {}", token))
39    }
40}
41
42impl From<Url> for AuthorizedAddress {
43    fn from(url: Url) -> Self {
44        let bearer_token = match url.username() {
45            "" => None,
46            username => Some(username.to_string()),
47        };
48
49        let mut url = url;
50        url.set_username("").expect("URL is always valid");
51
52        Self { url, bearer_token }
53    }
54}