Server-Sent Events (#75)

Example usage:

```rust
use axum::{prelude::*, sse::{sse, Event, KeepAlive}};
use tokio_stream::StreamExt as _;
use futures::stream::{self, Stream};
use std::{
    time::Duration,
    convert::Infallible,
};

let app = route("/sse", sse(make_stream).keep_alive(KeepAlive::default()));

async fn make_stream(
    // you can also put extractors here
) -> Result<impl Stream<Item = Result<Event, Infallible>>, Infallible> {
    // A `Stream` that repeats an event every second
    let stream = stream::repeat_with(|| Event::default().data("hi!"))
        .map(Ok)
        .throttle(Duration::from_secs(1));

    Ok(stream)
}
```

Implementation is based on [warp's](https://github.com/seanmonstar/warp/blob/master/src/filters/sse.rs)
This commit is contained in:
David Pedersen
2021-08-01 21:49:17 +02:00
committed by GitHub
parent c232c56de0
commit 6d787665d6
7 changed files with 589 additions and 1 deletions
+2 -1
View File
@@ -23,7 +23,7 @@ bytes = "1.0"
futures-util = "0.3"
http = "0.2"
http-body = "0.4"
hyper = { version = "0.14", features = ["server", "tcp", "http1"] }
hyper = { version = "0.14", features = ["server", "tcp", "http1", "stream"] }
pin-project = "1.0"
regex = "1.5"
serde = "1.0"
@@ -57,6 +57,7 @@ tracing = "0.1"
tracing-subscriber = "0.2"
uuid = { version = "0.8", features = ["serde", "v4"] }
async-session = "3.0.0"
tokio-stream = "0.1.7"
[dev-dependencies.tower]
version = "0.4"