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

64 lines
1.9 KiB
Rust
Raw Normal View History

2021-08-02 23:09:09 +02:00
//! Run with
//!
//! ```not_rust
//! cargo run -p example-sse
2021-08-02 23:09:09 +02:00
//! ```
2021-08-14 16:29:09 +01:00
use axum::{
2021-10-24 19:33:03 +02:00
error_handling::HandleErrorExt,
2021-08-14 16:29:09 +01:00
extract::TypedHeader,
http::StatusCode,
2021-08-23 17:51:30 +02:00
response::sse::{Event, Sse},
2021-11-01 22:13:37 +01:00
routing::{get, service_method_routing as service},
Router,
2021-08-14 16:29:09 +01:00
};
2021-08-01 21:49:17 +02:00
use futures::stream::{self, Stream};
use std::{convert::Infallible, net::SocketAddr, time::Duration};
use tokio_stream::StreamExt as _;
use tower_http::{services::ServeDir, trace::TraceLayer};
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", "example_sse=debug,tower_http=debug")
}
tracing_subscriber::fmt::init();
2021-08-01 21:49:17 +02:00
let static_files_service =
service::get(ServeDir::new("examples/sse/assets").append_index_html_on_directories(true))
.handle_error(|error: std::io::Error| {
(
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)
.throttle(Duration::from_secs(1));
2021-08-23 17:51:30 +02:00
Sse::new(stream)
2021-08-01 21:49:17 +02:00
}