expression

Axum: name and identify SSE events

An SSE event can carry an event type, an identifier and data. A reconnecting client can report its last event identifier, but the application must implement any replay or deduplication policy itself. A fixed in-memory event demonstrates the fields without promising delivery guarantees. In-memory standalone Cargo example. Expected stdout (not executed): three fields verified Common mistake: Assuming an event ID provides automatic reliable replay.

Formal Syntax & Structure

rust syntaxrust
Event::default().event(name).id(id).data(value)

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::response::{IntoResponse, sse::{Event, Sse}};    use futures_util::stream;    use std::convert::Infallible;    let event = Event::default().event("stock").id("7").data("available");    let res = Sse::new(stream::iter([Ok::<_, Infallible>(event)])).into_response();    let bytes = to_bytes(res.into_body(), 128).await.unwrap();    let text = std::str::from_utf8(&bytes).unwrap();    for (key, value) in [("event:", "stock"), ("id:", "7"), ("data:", "available")] {        assert!(text.lines().any(|line| line.strip_prefix(key).is_some_and(|v| v.trim_start() == value)));    }    println!("three fields verified");}
Rust Reference