sse

package
v1.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 11 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sse provides support for HTML Server-Sent Events.

See the Server-Sent Events specification: https://html.spec.whatwg.org/multipage/server-sent-events.html

Index

Constants

View Source
const (
	// DefaultRetry is the default retry interval used for SSE reconnection.
	DefaultRetry = 3 * time.Second
	// DefaultEventType is the default SSE event type.
	DefaultEventType = "message"
)
View Source
const DefaultKeepAliveInterval = 15 * time.Second

DefaultKeepAliveInterval is the default interval between keep-alive comments, as recommended by the SSE specification authoring notes.

Variables

View Source
var (
	// ErrEventTooLarge reports that an SSE event exceeded the configured size limit.
	ErrEventTooLarge = errors.New("sse: event too large")
	// ErrStreamClosed reports that the SSE stream was closed by client.
	ErrStreamClosed = errors.New("sse: stream is closed")
	// ErrNoReconnect means the server explicitly requested no reconnect.
	//
	// Returned when the server responds with [http.StatusNoContent].
	ErrNoReconnect = errors.New("sse: no reconnect")
	// ErrMaxRetriesExceeded means the configured reconnect retry budget was exhausted.
	ErrMaxRetriesExceeded = errors.New("sse: max retries exceeded")
)

Functions

func IsReconnectableError

func IsReconnectableError(err error) bool

IsReconnectableError reports whether err should trigger automatic SSE reconnect.

func KeepAlive added in v1.26.0

func KeepAlive[E any](ctx context.Context, s Sender[E]) error

KeepAlive writes a keep-alive comment to s every DefaultKeepAliveInterval until ctx is canceled, then returns nil.

It is used as the default value of the generated KeepAlive field, keeping idle connections open. Use KeepAliveEvery to configure the interval and comment.

func KeepAliveEvery added in v1.26.0

func KeepAliveEvery[E any](ctx context.Context, s Sender[E], interval time.Duration, comment string) error

KeepAliveEvery writes comment to s every interval until ctx is canceled, then returns nil. A write error is returned as-is and stops the loop.

A non-positive interval uses DefaultKeepAliveInterval.

Types

type Client

type Client[E any] interface {
	Next(ctx context.Context) (E, error)
	All(ctx context.Context) iter.Seq2[E, error]
	State() (state State, latestErr error)
	Close() error
}

Client represents SSE client.

type ClientOptions

type ClientOptions struct {
	LastEventID       string
	Retry             *time.Duration
	MaxRetries        int
	InitialBufferCap  int
	MaxEventSize      int
	RetryErrorHandler RetryErrorHandler
}

ClientOptions configures SSE client behavior.

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder reads an SSE stream as defined by the HTML Standard.

func NewDecoder

func NewDecoder(r io.Reader,
	initialBufferCap, maxEventSize int,
	lastEventID string,
	retry *time.Duration,
) *Decoder

NewDecoder creates a decoder for an SSE event stream.

initialBufferCap controls the reusable line buffer size, zero uses the package default. maxEventSize limits the number of bytes accepted for one event, zero disables the limit. lastEventID and retry initialize reconnect state for a resumed stream.

func (*Decoder) Decode

func (d *Decoder) Decode() (Event, error)

Decode reads and returns the next dispatched SSE event.

Events without data are skipped. Decoder.LastEventID and Decoder.Retry are updated as valid id and retry fields are parsed, even before an event is returned.

If the stream ends before an event is dispatched, Decode returns io.EOF and discards the incomplete event. If maxEventSize is exceeded, Decode returns the event fields parsed so far together with ErrEventTooLarge and drains the rest of that event.

func (*Decoder) LastEventID

func (d *Decoder) LastEventID() string

LastEventID returns the current stream-level last event ID.

It is updated when an id field is parsed and is intended to be sent as the Last-Event-ID header on reconnect. It is not the same as Event.ID, which is set only from the id field of the returned event.

func (*Decoder) Retry

func (d *Decoder) Retry() time.Duration

Retry returns the current stream-level retry interval.

It starts with configured default, and is updated when a valid retry field is parsed.

type Encoder added in v1.26.0

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder writes an SSE stream as defined by the HTML Standard.

Encoder is not safe for concurrent use.

func NewEncoder added in v1.26.0

func NewEncoder(w io.Writer, opts ...EncoderOption) *Encoder

NewEncoder creates an encoder writing an SSE event stream to w.

Every written event is flushed, so that it is delivered without waiting for the underlying buffer to fill. If w is an http.ResponseWriter, flushing is done via http.ResponseController, unwrapping the writer if needed. Otherwise, w is flushed if it implements `Flush() error` or http.Flusher.

func (*Encoder) Comment added in v1.26.0

func (e *Encoder) Comment(text string) error

Comment writes an SSE comment, e.g. to keep the connection alive, and flushes the stream.

func (*Encoder) Encode added in v1.26.0

func (e *Encoder) Encode(event Event) error

Encode writes event to the stream and flushes it.

Only the fields that are set are written: a time.Duration pointer for Retry, and non-empty ID, Type and Data. This allows metadata-only frames, e.g. a retry-only frame that updates the client reconnect delay without dispatching an event. An empty Data means no data field is written, so such an event is not dispatched by the client.

func (*Encoder) Flush added in v1.26.0

func (e *Encoder) Flush() error

Flush flushes the underlying writer.

type EncoderOption added in v1.26.0

type EncoderOption func(*Encoder)

EncoderOption configures an Encoder.

func WithEncoderBufferCap added in v1.26.0

func WithEncoderBufferCap(bytes int) EncoderOption

WithEncoderBufferCap sets the retained capacity of the encoder line buffer.

The buffer grows to fit a larger event and is shrunk back to this capacity afterwards, so one big event does not permanently retain memory. Zero uses the package default.

type Event

type Event struct {
	// ID is the value of the id field. It can be empty if the field is not set.
	//
	// Use [Decoder.LastEventID] to get the current last event ID of the stream.
	ID string
	// Type is the value of the event field. It defaults to "message".
	Type string
	// Data is the event data accumulated from the data fields.
	Data string
	// Retry is the reconnection delay. It is nil if the event has no retry field.
	//
	// Use [Decoder.Retry] to get the current retry interval of the stream.
	Retry *time.Duration
}

Event is a single Server-Sent Events event.

type RetryErrorHandler

type RetryErrorHandler func(ctx context.Context, connectErr error)

RetryErrorHandler is called after a retry reconnect attempt fails.

type Sender added in v1.26.0

type Sender[E any] interface {
	// Send encodes event and writes it to the stream, flushing it.
	Send(ctx context.Context, event E) error
	// Comment writes a comment to the stream, e.g. to keep it alive.
	Comment(ctx context.Context, text string) error
}

Sender sends events to an SSE stream.

A Sender is safe for concurrent use, so events and keep-alive comments may be written from different goroutines.

func NewSender added in v1.26.0

func NewSender[E any](e *Encoder, encode func(event E) (Event, error)) Sender[E]

NewSender returns a Sender writing events to e, encoding them with encode.

type State

type State int

State is the SSE stream client state.

const (
	// StateConnecting indicates that the SSE connection is being established.
	// It can indicate that the stream is reconnecting and waiting for the
	// retry period.
	StateConnecting State = iota
	// StateOpen indicates that the SSE connection is active and receiving events.
	StateOpen
	// StateClosed indicates that the SSE connection has been closed by either
	// the client or the server, and no further events will be received.
	StateClosed
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL