Volga
Home
API Docs
GitHub
  • English
  • Русский
Home
API Docs
GitHub
  • English
  • Русский
  • Home
  • Basics

    • Quick Start
    • Route Parameters
    • Query Parameters
    • Route Groups
    • Headers
  • Data Formats

    • Handling JSON
    • Handling Form Data
    • Working with Files
    • Server-Sent Events (SSE)
  • Protocols

    • HTTP/1 and HTTP/2
    • HTTPS
    • WebSockets & WebTransport
  • Advanced

    • Custom Middleware
    • Response Compression
    • Request Decompression
    • Global Error Handling
    • Dependency Injection
    • Tracing & Logging
    • Static Files
    • CORS (Cross-Origin Resource Sharing)
    • Cookies
    • Request cancellation
    • Custom Handling of HEAD, OPTIONS, and TRACE Methods

Server-Sent Events (SSE)

Volga includes built-in support for Server-Sent Events (SSE), allowing you to implement real-time, one-way communication from the server to the client in your web applications. This feature is available by default and is compatible with both HTTP/1 and HTTP/2 protocols.

Basic Usage

The example below demonstrates how to create a simple SSE endpoint. It maps a GET request to /events, sets the text/event-stream content type, and continuously sends the message "Hello, world!" once per second until the client disconnects:

use volga::{App, error::Error, http::sse::Message, sse};
use futures_util::stream::repeat_with;
use std::time::Duration;
use tokio_stream::StreamExt;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let mut app = App::new();

    app.map_get("/events", || async {
        // Create a stream of messages sent every second
        let stream = repeat_with(|| Message::new().data("Hello, world!"))
            .map(Ok::<_, Error>)
            .throttle(Duration::from_secs(1));

        sse!(stream)
    });

    app.run().await
}

Customizing Messages

Volga provides the Message struct to help you build and customize SSE messages.

For simple text messages, use the data() method as shown above. If you need to send structured data, such as JSON, use the json() method, which accepts any type that implements the serde::Serialize trait:

use volga::http::sse::Message;
use serde::Serialize;

#[derive(Serialize)]
struct SseData {
    data: String,
}

let payload = SseData { data: "Hello, world!".into() };
Message::new().json(payload);

In addition to setting the message data, the Message builder also supports customization of the event name, ID, comments, and client reconnection retry interval. For details on the SSE message format, refer to MDN's guide.

You may also find a full example here.

Last Updated:
Prev
Working with Files