sse.rs (1698B)
1 use axum::{body::Body, http::{StatusCode, header}, response::Response}; 2 3 pub fn patch_elements(html: &str) -> Response { 4 patch_elements_with_options(html, None, None) 5 } 6 7 /// Send multiple patch events in a single SSE response. 8 pub fn patch_multiple(fragments: &[&str]) -> Response { 9 let mut events = Vec::new(); 10 for html in fragments { 11 let mut data_lines = Vec::new(); 12 for line in html.lines() { 13 data_lines.push(format!("data: elements {line}")); 14 } 15 events.push(format!("event: datastar-patch-elements\n{}", data_lines.join("\n"))); 16 } 17 18 let body = format!("{}\n\n", events.join("\n\n")); 19 20 Response::builder() 21 .status(StatusCode::OK) 22 .header(header::CONTENT_TYPE, "text/event-stream") 23 .header(header::CACHE_CONTROL, "no-cache") 24 .header("X-Accel-Buffering", "no") 25 .body(Body::from(body)) 26 .unwrap() 27 } 28 29 fn patch_elements_with_options( 30 html: &str, 31 selector: Option<&str>, 32 mode: Option<&str>, 33 ) -> Response { 34 let mut data_lines = Vec::new(); 35 if let Some(sel) = selector { 36 data_lines.push(format!("data: selector {sel}")); 37 } 38 if let Some(m) = mode { 39 data_lines.push(format!("data: mode {m}")); 40 } 41 for line in html.lines() { 42 data_lines.push(format!("data: elements {line}")); 43 } 44 45 let body = format!("event: datastar-patch-elements\n{}\n\n", data_lines.join("\n")); 46 47 Response::builder() 48 .status(StatusCode::OK) 49 .header(header::CONTENT_TYPE, "text/event-stream") 50 .header(header::CACHE_CONTROL, "no-cache") 51 .header("X-Accel-Buffering", "no") 52 .body(Body::from(body)) 53 .unwrap() 54 }