mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-16 00:00:18 +02:00
* More robust asset paths in examples * Update examples/low-level-rustls/src/main.rs Co-authored-by: Jonas Platte <[email protected]> * format Co-authored-by: Jonas Platte <[email protected]>
73 lines
2.1 KiB
Rust
73 lines
2.1 KiB
Rust
//! Run with
|
|
//!
|
|
//! ```not_rust
|
|
//! cd examples && cargo run -p example-sse
|
|
//! ```
|
|
|
|
use axum::{
|
|
extract::TypedHeader,
|
|
http::StatusCode,
|
|
response::sse::{Event, Sse},
|
|
routing::{get, get_service},
|
|
Router,
|
|
};
|
|
use futures::stream::{self, Stream};
|
|
use std::{convert::Infallible, net::SocketAddr, path::PathBuf, time::Duration};
|
|
use tokio_stream::StreamExt as _;
|
|
use tower_http::{services::ServeDir, trace::TraceLayer};
|
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
|
|
|
#[tokio::main]
|
|
async fn main() {
|
|
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();
|
|
|
|
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),
|
|
)
|
|
});
|
|
|
|
// build our application with a route
|
|
let app = Router::new()
|
|
.fallback(static_files_service)
|
|
.route("/sse", get(sse_handler))
|
|
.layer(TraceLayer::new_for_http());
|
|
|
|
// run it
|
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
|
tracing::debug!("listening on {}", addr);
|
|
axum::Server::bind(&addr)
|
|
.serve(app.into_make_service())
|
|
.await
|
|
.unwrap();
|
|
}
|
|
|
|
async fn sse_handler(
|
|
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
|
|
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
|
|
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));
|
|
|
|
Sse::new(stream).keep_alive(
|
|
axum::response::sse::KeepAlive::new()
|
|
.interval(Duration::from_secs(1))
|
|
.text("keep-alive-text"),
|
|
)
|
|
}
|