expression

Axum: server-sent events

Server-sent events carry text events from a server to a client over an HTTP response. Axum formats Event values using SSE framing and chooses the event-stream media type. Test a finite stream so collection can finish. SSE is not a bidirectional messaging protocol. In-memory standalone Cargo example. Expected stdout (not executed): event received Common mistake: Collecting an intentionally endless SSE stream without a stopping condition.

Formal Syntax & Structure

rust syntaxrust
Sse::new(stream_of_events)

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::{routing::get, response::sse::{Event, Sse}, http::header};    use futures_util::stream;    use std::convert::Infallible;    let app = Router::new().route("/events", get(|| async {        Sse::new(stream::iter([Ok::<_, Infallible>(Event::default().data("ready"))]))    }));    let res = app.oneshot(Request::builder().uri("/events").body(Body::empty()).unwrap()).await.unwrap();    assert_eq!(res.headers()[header::CONTENT_TYPE], "text/event-stream");    let bytes = to_bytes(res.into_body(), 128).await.unwrap();    let text = std::str::from_utf8(&bytes).unwrap();    assert!(text.lines().any(|line| line.starts_with("data:") && line[5..].trim_start() == "ready"));    println!("event received");}
Rust Reference