Module axum::sse[][src]

Expand description

Server-Sent Events (SSE)

Example

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(
) -> 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)
}

SSE handlers can also use extractors:

use axum::{prelude::*, sse::{sse, Event}, extract::{RequestParts, FromRequest}};
use tokio_stream::StreamExt as _;
use futures::stream::{self, Stream};
use std::{
    time::Duration,
    convert::Infallible,
};
use http::{HeaderMap, StatusCode};

/// An extractor that authorizes requests.
struct RequireAuth;

#[async_trait::async_trait]
impl<B> FromRequest<B> for RequireAuth
where
    B: Send,
{
    type Rejection = StatusCode;

    async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
        // Put your auth logic here...
    }
}

let app = route("/sse", sse(make_stream));

async fn make_stream(
    // Run `RequireAuth` for each request before initiating the stream.
    _auth: RequireAuth,
) -> Result<impl Stream<Item = Result<Event, Infallible>>, Infallible> {
    // ...
}

Structs

Server-sent event

Configure the interval between keep-alive messages, the content of each message, and the associated stream.

Response future for Sse.

Service that handlers streams of Server-sent events.

Traits

Trait for async functions that can be used to handle Server-sent event requests.

Functions

Create a new Sse service that will call the closure to produce a stream of Events.