Files
axum/examples/sse/src/main.rs
T

73 lines
2.1 KiB
Rust
Raw Normal View History

2021-08-02 23:09:09 +02:00
//! Run with
//!
//! ```not_rust
2022-04-29 18:53:41 +02:00
//! cd examples && cargo run -p example-sse
2021-08-02 23:09:09 +02:00
//! ```
2021-08-14 16:29:09 +01:00
use axum::{
extract::TypedHeader,
http::StatusCode,
2021-08-23 17:51:30 +02:00
response::sse::{Event, Sse},
2021-11-16 20:49:07 +01:00
routing::{get, get_service},
Router,
2021-08-14 16:29:09 +01:00
};
2021-08-01 21:49:17 +02:00
use futures::stream::{self, Stream};
2022-06-15 22:42:49 +02:00
use std::{convert::Infallible, net::SocketAddr, path::PathBuf, time::Duration};
2021-08-01 21:49:17 +02:00
use tokio_stream::StreamExt as _;
use tower_http::{services::ServeDir, trace::TraceLayer};
2022-03-06 12:37:00 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2021-08-01 21:49:17 +02:00
#[tokio::main]
async fn main() {
2022-03-06 12:37:00 +01:00
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG")
.unwrap_or_else(|_| "example_sse=debug,tower_http=debug".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();
2021-08-01 21:49:17 +02:00
2022-06-15 22:42:49 +02:00
let assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets");
let static_files_service = get_service(
ServeDir::new(assets_dir).append_index_html_on_directories(true),
)
.handle_error(|error: std::io::Error| async move {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", error),
)
});
2021-08-01 21:49:17 +02:00
// build our application with a route
let app = Router::new()
2021-10-27 17:52:41 +02:00
.fallback(static_files_service)
2021-08-14 16:29:09 +01:00
.route("/sse", get(sse_handler))
.layer(TraceLayer::new_for_http());
2021-08-01 21:49:17 +02:00
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
2021-08-01 21:49:17 +02:00
.serve(app.into_make_service())
.await
.unwrap();
}
2021-08-14 16:29:09 +01:00
async fn sse_handler(
2021-08-01 21:49:17 +02:00
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
2021-08-14 16:29:09 +01:00
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
2021-08-01 21:49:17 +02:00
println!("`{}` connected", user_agent.as_str());
// A `Stream` that repeats an event every second
let stream = stream::repeat_with(|| Event::default().data("hi!"))
.map(Ok)
2022-06-15 22:42:49 +02:00
.throttle(Duration::from_secs(1));
2021-08-01 21:49:17 +02:00
2022-01-03 18:48:50 +01:00
Sse::new(stream).keep_alive(
axum::response::sse::KeepAlive::new()
.interval(Duration::from_secs(1))
.text("keep-alive-text"),
)
2021-08-01 21:49:17 +02:00
}