Skip to main content

async_wsocket/
lib.rs

1// Copyright (c) 2022-2024 Yuki Kishimoto
2// Distributed under the MIT software license
3
4//! Async WebSocket
5
6#![forbid(unsafe_code)]
7#![warn(clippy::large_futures)]
8#![cfg_attr(feature = "default", doc = include_str!("../README.md"))]
9
10#[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
11use std::net::SocketAddr;
12
13pub use futures_util;
14pub use url::{self, Url};
15
16pub mod message;
17#[cfg(not(target_arch = "wasm32"))]
18pub mod native;
19pub mod prelude;
20mod socket;
21#[cfg(target_arch = "wasm32")]
22pub mod wasm;
23
24pub use self::message::Message;
25#[cfg(not(target_arch = "wasm32"))]
26pub use self::native::Error;
27#[cfg(not(target_arch = "wasm32"))]
28pub use self::native::{HeaderMap, HeaderName, HeaderValue};
29pub use self::socket::WebSocket;
30#[cfg(target_arch = "wasm32")]
31pub use self::wasm::Error;
32
33#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
34pub enum ConnectionMode {
35    /// Direct
36    #[default]
37    Direct,
38    /// Custom proxy
39    #[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
40    Proxy(SocketAddr),
41}
42
43impl ConnectionMode {
44    /// Direct connection
45    #[inline]
46    pub fn direct() -> Self {
47        Self::Direct
48    }
49
50    /// Proxy
51    #[inline]
52    #[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
53    pub fn proxy(addr: SocketAddr) -> Self {
54        Self::Proxy(addr)
55    }
56}
57
58/// Connect
59#[inline]
60pub async fn connect(url: &Url, mode: &ConnectionMode) -> Result<WebSocket, Error> {
61    WebSocket::connect(url, mode).await
62}
63
64/// Connect with additional HTTP headers in the WebSocket upgrade request.
65#[cfg(not(target_arch = "wasm32"))]
66#[inline]
67pub async fn connect_with_headers(
68    url: &Url,
69    mode: &ConnectionMode,
70    headers: HeaderMap,
71) -> Result<WebSocket, Error> {
72    WebSocket::connect_with_headers(url, mode, headers).await
73}