Skip to content
Open
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
11 changes: 7 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
[package]
name = "reqwest-websocket"
version = "0.5.1"
name = "reqwest-websocket-julien-cpsn"
version = "0.6.0"
edition = "2021"
authors = ["Janosch Gräf <[email protected]>"]
authors = ["Janosch Gräf <[email protected]>", "julien-cpsn"]
description = "WebSocket connections with reqwest"
readme = "README.md"
homepage = "https://github.com/jgraef/reqwest-websocket"
Expand All @@ -21,12 +21,15 @@ rustdoc-args = ["--cfg", "docsrs"]

[features]
json = ["dep:serde", "dep:serde_json"]
middleware = ["reqwest-middleware"]

[dependencies]
# pin version, see https://github.com/jgraef/reqwest-websocket/pull/33
futures-util = { version = ">=0.3.31", default-features = false, features = ["sink"] }
reqwest = { version = "0.12", default-features = false }
reqwest-middleware = { version = "0.4.2", default-features = false, optional = true }
thiserror = "2"
anyhow = "1.0.99"
tracing = "0.1"
serde = { version = "1.0", default-features = false, optional = true }
serde_json = { version = "1.0", default-features = false, optional = true, features = ["alloc"] }
Expand All @@ -39,7 +42,7 @@ tungstenite = { version = "0.27", default-features = false, features = ["handsha

[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3", features = ["WebSocket", "CloseEvent", "ErrorEvent", "Event", "MessageEvent", "BinaryType"] }
tokio = { version = "1", default-features = false, features = ["sync", "macros"] }
tokio = { version = "1", default-features = false, features = ["sync", "macros", "io-util"] }

[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt"] }
Expand Down
68 changes: 52 additions & 16 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,13 @@ pub use crate::native::HandshakeError;
pub use crate::protocol::{CloseCode, Message};
pub use bytes::Bytes;
use futures_util::{Sink, SinkExt, Stream, StreamExt};
use reqwest::{Client, ClientBuilder, IntoUrl, RequestBuilder};
use reqwest::{IntoUrl};

#[cfg(not(feature = "middleware"))]
use reqwest::{RequestBuilder, ClientBuilder, Client};

#[cfg(feature = "middleware")]
use reqwest_middleware::{RequestBuilder, ClientBuilder, ClientWithMiddleware as Client};

/// Errors returned by `reqwest_websocket`.
#[derive(Debug, thiserror::Error)]
Expand Down Expand Up @@ -104,21 +110,45 @@ pub enum Error {
///
/// [`Request`]: reqwest::Request
/// [`Response`]: reqwest::Response
pub async fn websocket(url: impl IntoUrl) -> Result<WebSocket, Error> {
builder_http1_only(Client::builder())
.build()?
.get(url)
.upgrade()
.send()
.await?
.into_websocket()
.await
pub async fn websocket(url: impl IntoUrl) -> anyhow::Result<WebSocket> {
#[cfg(not(feature = "middleware"))]
{
builder_http1_only(Client::builder())
.build()?
.get(url)
.upgrade()
.send()
.await?
.into_websocket()
.await
}

#[cfg(feature = "middleware")]
{
builder_http1_only(ClientBuilder::from_client(Client::default()))
.build()
.get(url)
.upgrade()
.send()
.await?
.into_websocket()
.await
}
}

#[inline]
#[cfg(not(target_arch = "wasm32"))]
fn builder_http1_only(builder: ClientBuilder) -> ClientBuilder {
builder.http1_only()
#[cfg(not(feature = "middleware"))]
{
builder.http1_only()
}

// TODO: use HTTP1 (not possible for the moment I guess)
#[cfg(feature = "middleware")]
{
builder
}
}

#[inline]
Expand Down Expand Up @@ -176,7 +206,7 @@ impl UpgradedRequestBuilder {
}

/// Sends the request and returns an [`UpgradeResponse`].
pub async fn send(self) -> Result<UpgradeResponse, Error> {
pub async fn send(self) -> anyhow::Result<UpgradeResponse> {
#[cfg(not(target_arch = "wasm32"))]
let inner = native::send_request(self.inner, &self.protocols).await?;

Expand Down Expand Up @@ -223,7 +253,7 @@ impl std::ops::Deref for UpgradeResponse {
impl UpgradeResponse {
/// Turns the response into a `WebSocket`.
/// This checks if the `WebSocket` handshake was successful.
pub async fn into_websocket(self) -> Result<WebSocket, Error> {
pub async fn into_websocket(self) -> anyhow::Result<WebSocket> {
#[cfg(not(target_arch = "wasm32"))]
let (inner, protocol) = self
.inner
Expand Down Expand Up @@ -273,11 +303,10 @@ impl WebSocket {
/// On wasm `code` must be [`CloseCode::Normal`], [`CloseCode::Iana(_)`],
/// or [`CloseCode::Library(_)`]. Furthermore `reason` must be at most 123
/// bytes long. Otherwise the call to [`close`][Self::close] will fail.
pub async fn close(self, code: CloseCode, reason: Option<&str>) -> Result<(), Error> {
pub async fn close(&mut self, code: CloseCode, reason: Option<&str>) -> Result<(), Error> {
#[cfg(not(target_arch = "wasm32"))]
{
let mut inner = self.inner;
inner
self.inner
.close(Some(tungstenite::protocol::CloseFrame {
code: code.into(),
reason: reason.unwrap_or_default().into(),
Expand Down Expand Up @@ -340,7 +369,14 @@ impl Sink<Message> for WebSocket {
#[cfg(test)]
pub mod tests {
use futures_util::{SinkExt, TryStreamExt};

#[cfg(not(feature = "middleware"))]
use reqwest::Client;

#[cfg(feature = "middleware")]
use reqwest_middleware::ClientWithMiddleware as Client;


#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::wasm_bindgen_test;

Expand Down
13 changes: 9 additions & 4 deletions src/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,20 @@ use crate::{
};
use reqwest::{
header::{HeaderName, HeaderValue},
RequestBuilder, Response, StatusCode, Version,
Response, StatusCode, Version,
};
use tungstenite::protocol::WebSocketConfig;

#[cfg(not(feature = "middleware"))]
use reqwest::RequestBuilder;

#[cfg(feature = "middleware")]
use reqwest_middleware::RequestBuilder;

pub async fn send_request(
request_builder: RequestBuilder,
protocols: &[String],
) -> Result<WebSocketResponse, Error> {
) -> anyhow::Result<WebSocketResponse> {
let (client, request_result) = request_builder.build_split();
let mut request = request_result?;

Expand Down Expand Up @@ -83,8 +89,7 @@ pub async fn send_request(
})
}

pub type WebSocketStream =
async_tungstenite::WebSocketStream<tokio_util::compat::Compat<reqwest::Upgraded>>;
pub type WebSocketStream = async_tungstenite::WebSocketStream<tokio_util::compat::Compat<reqwest::Upgraded>>;

/// Error during `Websocket` handshake.
#[derive(Debug, thiserror::Error)]
Expand Down