Skip to content

Commit

Permalink
add the ability to set the protocol(s) when creating a websocket clie…
Browse files Browse the repository at this point in the history
…nt (cloudflare#424)

* add the ability to set the protocol(s) when creating a websocket client

* fmt and clippy

---------

Co-authored-by: Kevin Flansburg <[email protected]>
  • Loading branch information
2 people authored and jdon committed Mar 27, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent ea3dad9 commit e6bb066
Showing 2 changed files with 27 additions and 2 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -133,4 +133,7 @@ dist
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.pnp.*

# RustRover
.idea
24 changes: 23 additions & 1 deletion worker/src/websocket.rs
Original file line number Diff line number Diff line change
@@ -63,7 +63,21 @@ 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> {
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(),
@@ -77,6 +91,14 @@ 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() {

0 comments on commit e6bb066

Please sign in to comment.