Crate trillium_sse

source ·
Expand description

§Trillium tools for server sent events

This primarily provides SseConnExt, an extension trait for trillium::Conn that has a with_sse_stream chainable method that takes a Stream where the Item implements Eventable.

Often, you will want this stream to be something like a channel, but the specifics of that are dependent on the event fanout characteristics of your application.

This crate implements Eventable for an Event type that you can use in your application, for String, and for &'static str. You can also implement Eventable for any type in your application.

§Example usage

use broadcaster::BroadcastChannel;
use trillium::{conn_try, conn_unwrap, log_error, Conn, Method, State};
use trillium_sse::SseConnExt;
use trillium_static_compiled::static_compiled;

type Channel = BroadcastChannel<String>;

fn get_sse(mut conn: Conn) -> Conn {
    let broadcaster = conn_unwrap!(conn.take_state::<Channel>(), conn);
    conn.with_sse_stream(broadcaster)
}

async fn post_broadcast(mut conn: Conn) -> Conn {
    let broadcaster = conn_unwrap!(conn.take_state::<Channel>(), conn);
    let body = conn_try!(conn.request_body_string().await, conn);
    log_error!(broadcaster.send(&body).await);
    conn.ok("sent")
}

fn main() {
    let handler = (
        static_compiled!("examples/static").with_index_file("index.html"),
        State::new(Channel::new()),
        |conn: Conn| async move {
            match (conn.method(), conn.path()) {
                (Method::Get, "/sse") => get_sse(conn),
                (Method::Post, "/broadcast") => post_broadcast(conn).await,
                _ => conn,
            }
        },
    );

    // trillium_smol::run(handler);
}

Structs§

Traits§

  • A trait that allows any Unpin + Send + Sync type to act as an event.
  • Extension trait for server sent events