expression

Axum SSE: encode multiline data safely

The SSE wire format represents multiline payloads using multiple data fields. Let the event builder encode the value instead of concatenating raw protocol lines. This checks field separation rather than exact whitespace. Standalone synthetic example. Expected stdout (not executed): 2 data fields Common mistake: Manually concatenating untrusted input into protocol fields.

Formal Syntax & Structure

rust syntaxrust
Event::default().data("line one\nline two")

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}, response::{IntoResponse, sse::{Event, Sse}}, extract::ws::{Message, WebSocketUpgrade, WebSocket}};use std::convert::Infallible;use futures_util::stream;use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    let event = Event::default().data("first\nsecond");    let res = Sse::new(stream::iter([Ok::<_, Infallible>(event)])).into_response();    let bytes = to_bytes(res.into_body(), 1024).await.unwrap();    let text = std::str::from_utf8(&bytes).unwrap();    let values: Vec<_> = text.lines().filter_map(|line| line.strip_prefix("data:")).map(str::trim_start).collect();    assert_eq!(values, ["first", "second"]);    println!("{} data fields", values.len());}
Rust Reference