trillium-websockets 0.9.0

websocket support for trillium.rs
Documentation

🔌 trillium-websockets — WebSocket handler

ci crates.io version docs.rs

WebSocket handler for Trillium, built on async-tungstenite. Accepts WebSocket upgrade requests and hands each connection to an async handler function or a WebSocketHandler implementation. Optionally supports the json feature for typed JSON message handling via JsonWebSocketHandler.

Example

use futures_lite::stream::StreamExt;
use trillium_websockets::{Message, WebSocketConn, websocket};

let app = websocket(|mut conn: WebSocketConn| async move {
    while let Some(Ok(Message::Text(input))) = conn.next().await {
        conn.send_string(format!("received: {input}")).await;
    }
});
// run with your chosen runtime adapter, e.g.:
// trillium_tokio::run(app);

Origin checking

Browsers do not apply CORS to websocket handshakes, so by default this handler accepts a handshake only if its Origin names the same host as the request's Host/:authority, or if there is no Origin at all (a non-browser client). Rejected handshakes receive a 403 Forbidden.

use trillium_websockets::{WebSocketConn, websocket};

# let handler = |_: WebSocketConn| async {};
websocket(handler).allow_origins(["https://app.example.com"]);

allow_origin_fn takes a predicate over the raw header for cases like a family of subdomains, and allow_any_origin opts out entirely.

Safety

This crate uses #![forbid(unsafe_code)].

License