FFFF GitHub - Tangerg/sse · GitHub
[go: up one dir, main page]

Skip to content
TangergPublic

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

 

History

46 Commits

Folders and files

Repository files navigation

sse

Go Reference CI

A small Go library for reading and writing Server-Sent Events (SSE).

It covers the core parsing and serialisation rules of the WHATWG HTML Living Standard §9.2 — BOM stripping, all three line endings (LF / CR / CRLF), the four fields (data, event, id, retry), the single-leading-space rule, and blank-line dispatch. It is a codec, not an EventSource client: automatic reconnection and request retries are the caller's responsibility.

Full API reference and runnable examples: pkg.go.dev/github.com/Tangerg/sse.

Requirements

Go 1.23 or later. Development and linting use the toolchain selected in go.mod.

Installation

go get github.com/Tangerg/sse

Writing

HTTP server

NewHTTPWriter sets the SSE response headers and flushes each event to the client immediately:

func handler(w http.ResponseWriter, r *http.Request) {
    sw := sse.NewHTTPWriter(w)

    if err := sw.Write(sse.Message{
        ID:    "1",
        Event: "update",
        Data:  []byte("hello world"),
    }); err != nil {
        return
    }
}

Headers set by NewHTTPWriter:

Header Value
Content-Type text/event-stream; charset=utf-8
Cache-Control no-cache (only if unset)

No Connection header is set: it is a hop-by-hop header that HTTP/2 forbids. Flushing goes through http.ResponseController, so it works through middleware that wraps the ResponseWriter.

Plain io.Writer

sw := sse.NewWriter(w)

if err := sw.Retry(5 * time.Second); err != nil {
    return err
}
return sw.Write(sse.Message{
    Event: "ping",
    Data:  []byte("{}"),
})

Every Write call emits a dispatchable event — a single data: line is written even when Data is empty, so an event carrying only a type (e.g. a refresh signal) is expressible. All fields must be valid UTF-8. An ID containing CR, LF, or NUL, or an Event containing CR or LF, is rejected with an error before any bytes are written. A write or flush failure ends the stream. Further calls return the same error.

Message.ID is the effective ID of the event. Supply the same ID on successive messages when they share a reconnection point. An empty ID clears that point, including when forwarding a message from a reader.

Retry and SetLastEventID can update a client's reconnection state without dispatching an event. An empty ID clears the reconnection point.

if err := sw.Retry(10 * time.Second); err != nil {
    return err
}
return sw.SetLastEventID("checkpoint-42")

Reading

HTTP client

NewHTTPReader requires HTTP 200 and checks the last supplied Content-Type header for the media type text/event-stream. Parameters, including charset, do not affect UTF-8 decoding.

resp, err := http.Get("https://example.com/events")
if err != nil { ... }
defer resp.Body.Close()

sr, err := sse.NewHTTPReader(resp)
if err != nil { ... }

for msg, err := range sr.Messages() {
    if err != nil { return err }
    fmt.Printf("event=%s data=%s\n", msg.Event, msg.Data)
}

A clean end of stream ends the loop without an error; malformed UTF-8 is decoded as U+FFFD per the Encoding Standard. A non-nil error means an I/O failure, ErrLineTooLong, or ErrEventTooLarge (both matchable with errors.Is). There is no context parameter: to interrupt a read blocked on a stalled connection, close resp.Body; to stop consuming, break out of the loop.

After the loop ends, LastEventID() and Retry() report the reconnection state. An ID takes effect at a blank line, including in a standalone frame. A retry takes effect at its line ending. An unterminated final field is discarded. Retry() returns the largest Go duration if the delay exceeds that range. A relay can forward the exact digits, including leading zeros, with sw.RetryMilliseconds(sr.RetryMilliseconds()) after a delay has been received.

if id := sr.LastEventID(); id != "" {
    req.Header.Set("Last-Event-ID", id)
} else {
    req.Header.Del("Last-Event-ID")
}
if d, ok := sr.Retry(); ok {
    time.Sleep(d)
}

Plain io.Reader

sr := sse.NewReader(r)
for msg, err := range sr.Messages() {
    ...
}

Large payloads

The default per-line limit is 64 KiB. Raise MaxLineBytes for larger fields, such as a serialised JSON object. The limit applies to the next line read.

sr := sse.NewReader(r)
sr.MaxLineBytes = 512 * 1024 // 512 KiB per line

A line exceeding the limit makes Messages yield a non-nil error. For untrusted streams, set MaxEventBytes to cap the byte length of Message.Data, including UTF-8 replacement characters and the newlines between data fields. A payload at the limit is accepted. A larger payload yields ErrEventTooLarge.

JSON data

Message.Data is []byte, so pass json.Marshal output directly and json.Unmarshal on receipt:

payload, err := json.Marshal(OrderEvent{OrderID: "ord_123", Status: "shipped"})
if err != nil { return err }
if err := sw.Write(sse.Message{ID: "1", Event: "order.updated", Data: payload}); err != nil {
    return err
}

for msg, err := range sr.Messages() {
    if err != nil { return err }
    var evt OrderEvent
    if err := json.Unmarshal(msg.Data, &evt); err != nil { return err }
}

Spec compliance

Implements the core parsing/serialisation of WHATWG HTML Living Standard §9.2: https://html.spec.whatwg.org/multipage/server-sent-events.html

Requirement §9.2 reference
Leading UTF-8 BOM stripped once §9.2.6
Malformed UTF-8 decoded with U+FFFD replacement §9.2.6 / Encoding Standard
All three line endings: LF, CR, CRLF §9.2.5 end-of-line
One leading space after : stripped from values §9.2.6
id values containing NUL ignored on read; rejected on write §9.2.6
retry accepts only ASCII decimal digits and preserves the full delay §9.2.6
595F Trailing LF removed from the data buffer on dispatch §9.2.6
Events with an empty data buffer discarded on read §9.2.6
Last-event-ID and retry persist across events §9.2.6
Incomplete final event (no trailing blank line) discarded §9.2.6
HTTP 200 status and media type text/event-stream enforced on read §9.2.3 / §9.2.5

Not implemented (out of scope): EventSource connection establishment and automatic reconnection. The package exposes the parsed last-event ID and retry delay so callers can implement that policy themselves.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0