2021-08-02 23:09:09 +02:00
|
|
|
//! Run with
|
|
|
|
//!
|
|
|
|
//! ```not_rust
|
|
|
|
//! cargo run --example sse --features=headers
|
|
|
|
//! ```
|
|
|
|
|
2021-08-14 17:29:09 +02:00
|
|
|
use axum::{
|
|
|
|
extract::TypedHeader,
|
|
|
|
prelude::*,
|
|
|
|
response::sse::{sse, Event, Sse},
|
|
|
|
routing::nest,
|
|
|
|
};
|
2021-08-01 21:49:17 +02:00
|
|
|
use futures::stream::{self, Stream};
|
|
|
|
use http::StatusCode;
|
|
|
|
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() {
|
2021-08-05 11:25:03 +02:00
|
|
|
// Set the RUST_LOG, if it hasn't been explicitly defined
|
|
|
|
if std::env::var("RUST_LOG").is_err() {
|
|
|
|
std::env::set_var("RUST_LOG", "sse=debug,tower_http=debug")
|
|
|
|
}
|
2021-08-05 19:43:03 +02:00
|
|
|
tracing_subscriber::fmt::init();
|
2021-08-01 21:49:17 +02:00
|
|
|
|
Move methods from `ServiceExt` to `RoutingDsl` (#160)
Previously, on `main`, this wouldn't compile:
```rust
let app = route("/", get(handler))
.layer(
ServiceBuilder::new()
.timeout(Duration::from_secs(10))
.into_inner(),
)
.handle_error(...)
.route(...); // <-- doesn't work
```
That is because `handle_error` would be
`axum::service::ServiceExt::handle_error` which returns `HandleError<_,
_, _, HandleErrorFromService>` which does _not_ implement `RoutingDsl`.
So you couldn't call `route`. This was caused by
https://github.com/tokio-rs/axum/pull/120.
Basically `handle_error` when called on a `RoutingDsl`, the resulting
service should also implement `RoutingDsl`, but if called on another
random service it should _not_ implement `RoutingDsl`.
I don't think thats possible by having `handle_error` on `ServiceExt`
which is implemented for any service, since all axum routers are also
services by design.
This resolves the issue by removing `ServiceExt` and moving its methods
to `RoutingDsl`. Then we have more tight control over what has a
`handle_error` method.
`service::OnMethod` now also has a `handle_error` so you can still
handle errors from random services, by doing
`service::any(svc).handle_error(...)`.
2021-08-08 14:30:51 +02:00
|
|
|
let static_files_service =
|
|
|
|
axum::service::get(ServeDir::new("examples/sse").append_index_html_on_directories(true))
|
|
|
|
.handle_error(|error: std::io::Error| {
|
|
|
|
Ok::<_, std::convert::Infallible>((
|
|
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
format!("Unhandled internal error: {}", error),
|
|
|
|
))
|
|
|
|
});
|
|
|
|
|
2021-08-01 21:49:17 +02:00
|
|
|
// build our application with a route
|
Move methods from `ServiceExt` to `RoutingDsl` (#160)
Previously, on `main`, this wouldn't compile:
```rust
let app = route("/", get(handler))
.layer(
ServiceBuilder::new()
.timeout(Duration::from_secs(10))
.into_inner(),
)
.handle_error(...)
.route(...); // <-- doesn't work
```
That is because `handle_error` would be
`axum::service::ServiceExt::handle_error` which returns `HandleError<_,
_, _, HandleErrorFromService>` which does _not_ implement `RoutingDsl`.
So you couldn't call `route`. This was caused by
https://github.com/tokio-rs/axum/pull/120.
Basically `handle_error` when called on a `RoutingDsl`, the resulting
service should also implement `RoutingDsl`, but if called on another
random service it should _not_ implement `RoutingDsl`.
I don't think thats possible by having `handle_error` on `ServiceExt`
which is implemented for any service, since all axum routers are also
services by design.
This resolves the issue by removing `ServiceExt` and moving its methods
to `RoutingDsl`. Then we have more tight control over what has a
`handle_error` method.
`service::OnMethod` now also has a `handle_error` so you can still
handle errors from random services, by doing
`service::any(svc).handle_error(...)`.
2021-08-08 14:30:51 +02:00
|
|
|
let app = nest("/", static_files_service)
|
2021-08-14 17:29:09 +02:00
|
|
|
.route("/sse", get(sse_handler))
|
Move methods from `ServiceExt` to `RoutingDsl` (#160)
Previously, on `main`, this wouldn't compile:
```rust
let app = route("/", get(handler))
.layer(
ServiceBuilder::new()
.timeout(Duration::from_secs(10))
.into_inner(),
)
.handle_error(...)
.route(...); // <-- doesn't work
```
That is because `handle_error` would be
`axum::service::ServiceExt::handle_error` which returns `HandleError<_,
_, _, HandleErrorFromService>` which does _not_ implement `RoutingDsl`.
So you couldn't call `route`. This was caused by
https://github.com/tokio-rs/axum/pull/120.
Basically `handle_error` when called on a `RoutingDsl`, the resulting
service should also implement `RoutingDsl`, but if called on another
random service it should _not_ implement `RoutingDsl`.
I don't think thats possible by having `handle_error` on `ServiceExt`
which is implemented for any service, since all axum routers are also
services by design.
This resolves the issue by removing `ServiceExt` and moving its methods
to `RoutingDsl`. Then we have more tight control over what has a
`handle_error` method.
`service::OnMethod` now also has a `handle_error` so you can still
handle errors from random services, by doing
`service::any(svc).handle_error(...)`.
2021-08-08 14:30:51 +02:00
|
|
|
.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);
|
2021-08-04 15:38:51 +02:00
|
|
|
axum::Server::bind(&addr)
|
2021-08-01 21:49:17 +02:00
|
|
|
.serve(app.into_make_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
|
2021-08-14 17:29:09 +02:00
|
|
|
async fn sse_handler(
|
2021-08-01 21:49:17 +02:00
|
|
|
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
|
2021-08-14 17:29:09 +02: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-14 17:29:09 +02:00
|
|
|
sse(stream)
|
2021-08-01 21:49:17 +02:00
|
|
|
}
|