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
- Variables
- func IsReconnectableError(err error) bool
- func KeepAlive[E any](ctx context.Context, s Sender[E]) error
- func KeepAliveEvery[E any](ctx context.Context, s Sender[E], interval time.Duration, comment string) error
- type Client
- type ClientOptions
- type Decoder
- type Encoder
- type EncoderOption
- type Event
- type RetryErrorHandler
- type Sender
- type State
Constants ¶
const ( // DefaultRetry is the default retry interval used for SSE reconnection. DefaultRetry = 3 * time.Second // DefaultEventType is the default SSE event type. DefaultEventType = "message" )
const DefaultKeepAliveInterval = 15 * time.Second
DefaultKeepAliveInterval is the default interval between keep-alive comments, as recommended by the SSE specification authoring notes.
Variables ¶
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 ¶
IsReconnectableError reports whether err should trigger automatic SSE reconnect.
func KeepAlive ¶ added in v1.26.0
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 ¶
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 ¶
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.
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
Comment writes an SSE comment, e.g. to keep the connection alive, and flushes the stream.
func (*Encoder) Encode ¶ added in v1.26.0
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.
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 ¶
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.
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 )