nhttp_sse (nhttp v1.0.0)

View Source

Server-Sent Events (SSE) helpers for nhttp.

Provides convenience functions for building SSE responses per the W3C Server-Sent Events specification.

Example Usage

handle_request(#{path := <<"/events">>}, State) ->
    Headers = nhttp_sse:headers(),
    Producer = fun(SendChunk) ->
        loop(SendChunk)
    end,
    Spec = nhttp_stream:producer(200, Headers, Producer),
    {stream, Spec, State}.

loop(SendChunk) ->
    Event = nhttp_sse:event(<<"update">>, <<"new data arrived">>),
    case SendChunk(Event) of
        ok -> loop(SendChunk);
        {error, _} -> ok
    end.

Summary

Functions

Encode a data field, properly handling multi-line data. Each line of data is prefixed with "data: " per the SSE spec.

Encode a data-only event (no event type). The data field may contain newlines. They will be properly encoded.

Encode a named event with data. The event type should not contain newlines.

Returns the required headers for an SSE response.

Returns SSE headers merged with additional headers.

Encode an event ID field. The id should not contain newlines.

Encode a retry field (reconnection time in milliseconds).

Functions

data/1

-spec data(iodata()) -> iolist().

Encode a data field, properly handling multi-line data. Each line of data is prefixed with "data: " per the SSE spec.

event(Data)

-spec event(iodata()) -> iolist().

Encode a data-only event (no event type). The data field may contain newlines. They will be properly encoded.

event(EventType, Data)

-spec event(iodata(), iodata()) -> iolist().

Encode a named event with data. The event type should not contain newlines.

headers()

-spec headers() -> [{binary(), binary()}].

Returns the required headers for an SSE response.

headers(Extra)

-spec headers([{binary(), binary()}]) -> [{binary(), binary()}].

Returns SSE headers merged with additional headers.

id(Id)

-spec id(iodata()) -> iolist().

Encode an event ID field. The id should not contain newlines.

retry(Ms)

-spec retry(non_neg_integer()) -> iolist().

Encode a retry field (reconnection time in milliseconds).