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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use std::fmt::Display;
use anyhow::bail;
use serde::{Deserialize, Serialize};
#[derive(PartialEq, PartialOrd, Ord, Hash, Eq, Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
#[serde(try_from = "&str")]
pub enum EndpointUrl {
Http(String),
Https(String),
Ws(String),
Wss(String),
}
impl Display for EndpointUrl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EndpointUrl::Http(s) | EndpointUrl::Https(s) | EndpointUrl::Ws(s) | EndpointUrl::Wss(s) => f.write_str(s),
}
}
}
impl TryFrom<&str> for EndpointUrl {
type Error = anyhow::Error;
fn try_from(s: &str) -> Result<Self, Self::Error> {
if s.starts_with("wss://") {
return Ok(EndpointUrl::Wss(s.to_string()));
}
if s.starts_with("ws://") {
return Ok(EndpointUrl::Ws(s.to_string()));
}
if s.starts_with("https://") {
return Ok(EndpointUrl::Https(s.to_string()));
}
if s.starts_with("http://") {
return Ok(EndpointUrl::Http(s.to_string()));
}
bail!("Invalid endpoint: {}", s)
}
}
#[cfg(test)]
mod test_from {
use super::*;
#[test]
fn test_from_str() {
assert_eq!(EndpointUrl::Wss("wss://foobar".to_string()), EndpointUrl::try_from("wss://foobar").unwrap());
}
}