mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-26 00:00:23 +02:00
Implement SSE using responses (#98)
This commit is contained in:
+10
-6
@@ -4,7 +4,12 @@
|
||||
//! cargo run --example sse --features=headers
|
||||
//! ```
|
||||
|
||||
use axum::{extract::TypedHeader, prelude::*, routing::nest, sse::Event};
|
||||
use axum::{
|
||||
extract::TypedHeader,
|
||||
prelude::*,
|
||||
response::sse::{sse, Event, Sse},
|
||||
routing::nest,
|
||||
};
|
||||
use futures::stream::{self, Stream};
|
||||
use http::StatusCode;
|
||||
use std::{convert::Infallible, net::SocketAddr, time::Duration};
|
||||
@@ -30,7 +35,7 @@ async fn main() {
|
||||
|
||||
// build our application with a route
|
||||
let app = nest("/", static_files_service)
|
||||
.route("/sse", axum::sse::sse(make_stream))
|
||||
.route("/sse", get(sse_handler))
|
||||
.layer(TraceLayer::new_for_http());
|
||||
|
||||
// run it
|
||||
@@ -42,10 +47,9 @@ async fn main() {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn make_stream(
|
||||
// sse handlers can also use extractors
|
||||
async fn sse_handler(
|
||||
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
|
||||
) -> Result<impl Stream<Item = Result<Event, Infallible>>, Infallible> {
|
||||
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
|
||||
println!("`{}` connected", user_agent.as_str());
|
||||
|
||||
// A `Stream` that repeats an event every second
|
||||
@@ -53,5 +57,5 @@ async fn make_stream(
|
||||
.map(Ok)
|
||||
.throttle(Duration::from_secs(1));
|
||||
|
||||
Ok(stream)
|
||||
sse(stream)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user