Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
24 changes: 23 additions & 1 deletion worker/src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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() {
Expand Down
Loading