Implement SSE using responses (#98)

This commit is contained in:
Kai Jewson
2021-08-14 17:29:09 +02:00
committed by GitHub
parent 045287aef9
commit 9cd543401f
7 changed files with 404 additions and 540 deletions
+10 -6
View File
@@ -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)
}