Skip to content

Commit 3e302df

Browse files
j-whitekflansburg
andauthored
add the ability to set the protocol(s) when creating a websocket client (#424)
* add the ability to set the protocol(s) when creating a websocket client * fmt and clippy --------- Co-authored-by: Kevin Flansburg <[email protected]>
1 parent c021d7a commit 3e302df

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-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

+23-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,21 @@ 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+
WebSocket::connect_with_protocols(url, None).await
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(
78+
mut url: Url,
79+
protocols: Option<Vec<&str>>,
80+
) -> Result<WebSocket> {
6781
let scheme: String = match url.scheme() {
6882
"ws" => "http".into(),
6983
"wss" => "https".into(),
@@ -77,6 +91,14 @@ impl WebSocket {
7791
let mut req = Request::new(url.as_str(), Method::Get)?;
7892
req.headers_mut()?.set("upgrade", "websocket")?;
7993

94+
match protocols {
95+
None => {}
96+
Some(v) => {
97+
req.headers_mut()?
98+
.set("Sec-WebSocket-Protocol", v.join(",").as_str())?;
99+
}
100+
}
101+
80102
let res = Fetch::Request(req).send().await?;
81103

82104
match res.websocket() {

0 commit comments

Comments
 (0)