Repository navigation
Expand file tree
/
Copy pathsocket.rs
More file actions
75 lines (63 loc) · 1.95 KB
/
Copy pathsocket.rs
File metadata and controls
75 lines (63 loc) · 1.95 KB
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
65
66
67
68
69
70
71
72
73
74
75
//! Socket.IO (Engine.IO v4) WebSocket URL for the TinyHumans backend.
use url::Url;
/// Build a Socket.IO WebSocket URL from an HTTP(S) API base (e.g. `https://api.tinyhumans.ai`).
pub fn websocket_url(http_or_https_base: &str) -> String {
let Ok(mut url) = Url::parse(http_or_https_base) else {
return http_or_https_base.to_string();
};
let scheme = match url.scheme() {
"https" => "wss",
"http" => "ws",
other => other,
}
.to_string();
let _ = url.set_scheme(&scheme);
// Ensure path ends with /socket.io/ and includes required query params
url.set_path(&format!("{}/socket.io/", url.path().trim_end_matches('/')));
url.set_query(Some("EIO=4&transport=websocket"));
url.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn converts_https_to_wss() {
let url = websocket_url("https://api.tinyhumans.ai");
assert_eq!(
url,
"wss://api.tinyhumans.ai/socket.io/?EIO=4&transport=websocket"
);
}
#[test]
fn converts_http_to_ws() {
let url = websocket_url("http://localhost:3000");
assert_eq!(
url,
"ws://localhost:3000/socket.io/?EIO=4&transport=websocket"
);
}
#[test]
fn passes_through_unknown_scheme() {
let url = websocket_url("ftp://example.com");
assert_eq!(
url,
"ftp://example.com/socket.io/?EIO=4&transport=websocket"
);
}
#[test]
fn strips_trailing_slash() {
let url = websocket_url("https://api.tinyhumans.ai/");
assert_eq!(
url,
"wss://api.tinyhumans.ai/socket.io/?EIO=4&transport=websocket"
);
}
#[test]
fn strips_multiple_trailing_slashes() {
let url = websocket_url("https://api.tinyhumans.ai///");
assert_eq!(
url,
"wss://api.tinyhumans.ai/socket.io/?EIO=4&transport=websocket"
);
}
}