Skip to content

Commit 470b9b1

Browse files
committed
add the ability to set the protocol(s) when creating a websocket client
1 parent c57f7a6 commit 470b9b1

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

.gitignore

+4-1
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,7 @@ dist
133133
.yarn/unplugged
134134
.yarn/build-state.yml
135135
.yarn/install-state.gz
136-
.pnp.*
136+
.pnp.*
137+
138+
# RustRover
139+
.idea

worker/src/websocket.rs

+19-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,18 @@ impl WebSocket {
6363
///
6464
/// Response::error("never got a message echoed back :(", 500)
6565
/// ```
66-
pub async fn connect(mut url: Url) -> Result<WebSocket> {
66+
pub async fn connect(url: Url) -> Result<WebSocket> {
67+
return WebSocket::connect_with_protocols(url, None);
68+
}
69+
70+
/// Attempts to establish a [`WebSocket`] connection to the provided [`Url`] and protocol.
71+
///
72+
/// # Example:
73+
/// ```rust,ignore
74+
/// let ws = WebSocket::connect_with_protocols("wss://echo.zeb.workers.dev/".parse()?, Some(vec!["GiggleBytes"])).await?;
75+
///
76+
/// ```
77+
pub async fn connect_with_protocols(mut url: Url, protocols: Option<Vec<&str>>) -> Result<WebSocket> {
6778
let scheme: String = match url.scheme() {
6879
"ws" => "http".into(),
6980
"wss" => "https".into(),
@@ -77,6 +88,13 @@ impl WebSocket {
7788
let mut req = Request::new(url.as_str(), Method::Get)?;
7889
req.headers_mut()?.set("upgrade", "websocket")?;
7990

91+
match protocols {
92+
None => {}
93+
Some(v) => {
94+
req.headers_mut()?.set("Sec-WebSocket-Protocol", protocols.join(","))?;
95+
}
96+
}
97+
8098
let res = Fetch::Request(req).send().await?;
8199

82100
match res.websocket() {

0 commit comments

Comments
 (0)