Skip to content

Commit

Permalink
add the ability to set the protocol(s) when creating a websocket client
Browse files Browse the repository at this point in the history
  • Loading branch information
j-white committed Dec 10, 2023
1 parent c57f7a6 commit 591f870
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,7 @@ dist
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.pnp.*

# RustRover
.idea
20 changes: 19 additions & 1 deletion worker/src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,18 @@ impl WebSocket {
///
/// Response::error("never got a message echoed back :(", 500)
/// ```
pub async fn connect(mut url: Url) -> Result<WebSocket> {
pub async fn connect(url: Url) -> Result<WebSocket> {
return WebSocket::connect_with_protocols(url, None).await;
}

/// Attempts to establish a [`WebSocket`] connection to the provided [`Url`] and protocol.
///
/// # Example:
/// ```rust,ignore
/// let ws = WebSocket::connect_with_protocols("wss://echo.zeb.workers.dev/".parse()?, Some(vec!["GiggleBytes"])).await?;
///
/// ```
pub async fn connect_with_protocols(mut url: Url, protocols: Option<Vec<&str>>) -> Result<WebSocket> {
let scheme: String = match url.scheme() {
"ws" => "http".into(),
"wss" => "https".into(),
Expand All @@ -77,6 +88,13 @@ impl WebSocket {
let mut req = Request::new(url.as_str(), Method::Get)?;
req.headers_mut()?.set("upgrade", "websocket")?;

match protocols {
None => {}
Some(v) => {
req.headers_mut()?.set("Sec-WebSocket-Protocol", v.join(",").as_str())?;
}
}

let res = Fetch::Request(req).send().await?;

match res.websocket() {
Expand Down

0 comments on commit 591f870

Please sign in to comment.