sse

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package sse reads server-sent event streams (text/event-stream), as the HTML standard defines them, and keeps a stream going across dropped connections.

Index

Constants

This section is empty.

Variables

View Source
var ErrStreamFailed = errors.New("event stream failed")

ErrStreamFailed wraps the error that ended a stream after its last allowed reconnect.

Functions

func Follow

func Follow(ctx context.Context, opts FollowOptions, open func(ctx context.Context) (*http.Response, error), handle func(Event) (stop bool, err error)) error

Follow opens a stream with open and reads it with Read. When the connection drops before handle stops it, Follow reopens it after a backoff, up to MaxReconnects times in a row (a stream that delivers events resets the count). Servers that replay earlier events on a new connection make handle see them again; handle should be idempotent. open returns the response; a non-2xx status is returned as is, without a reconnect.

func HandlerError

func HandlerError(err error) error

HandlerError wraps err so Follow returns it instead of reconnecting. Handlers return it for errors in their own logic (bad JSON, a write to stdout failing).

func Read

func Read(ctx context.Context, r io.Reader, handle func(Event) (stop bool, err error)) error

Read parses r and calls handle for every event until r ends, handle returns stop=true or an error, or ctx ends. It returns nil when the stream ended or handle stopped it.

Types

type Event

type Event struct {
	Name string
	Data string
	ID   string
}

Event is one dispatched event. Name is "message" when the stream gave no event field.

type FollowOptions

type FollowOptions struct {
	// MaxReconnects is how many times a dropped connection is reopened
	// before giving up (default 5).
	MaxReconnects int
	// Backoff is the first delay before reconnecting; it doubles up to
	// 10 s (default 1 s).
	Backoff time.Duration
	// Sleep waits between attempts; tests replace it.
	Sleep func(ctx context.Context, d time.Duration) error
}

FollowOptions controls Follow.

type StatusError

type StatusError struct{ Response *http.Response }

StatusError is a stream that answered with a non-2xx status. The caller owns Response (its body is unread) and turns it into an API error.

func (*StatusError) Error

func (e *StatusError) Error() string

Jump to

Keyboard shortcuts

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