Package ssehandler
Overview
Package ssehandler builds an HTTP handler that streams server-sent events from one streaming operation: a func(context.Context, Params) (iter.Seq2[Event, error], error).
The operation's two errors mean different things:
- The returned error is a setup error, known before anything is streamed, so the handler responds with a problem and the right status, as a JSON handler would.
- An error yielded by the iterator happens after the response has started. The handler sends it as a final event of type "error", whose data is the problem as JSON, and ends the stream.
While the stream is idle, the handler sends a comment every keep-alive interval, so proxies don't drop the connection. The stream ends when the iterator ends, the client disconnects, or the server starts shutting down (see server.Draining); the client then reconnects, to another instance if this one is going away.
Index
Constants
const (
DefaultKeepAlive = 15 * time.Second
DefaultWriteTimeout = 10 * time.Second
)Defaults, used unless a With method changes them.
Types
Builder source
type Builder[Request jsonhandler.WireRequest[Params], Params, Event any] struct {
// contains filtered or unexported fields
}Builder configures an SSE handler. Its With methods return a modified copy.
New source
func New[Request jsonhandler.WireRequest[Params], Params, Event any](
op func(context.Context, Params) (iter.Seq2[Event, error], error),
toEvent func(Event) (sse.Event, error),
) Builder[Request, Params, Event]New returns a Builder for a handler that streams the events of op, converting each with toEvent. The wire request is the zero Request: the body isn't read, so Params reads only the path and query. It panics if op or toEvent is nil.
(Builder[Request, Params, Event]) Handler source
func (b Builder[Request, Params, Event]) Handler() http.HandlerFuncHandler returns the handler.
(Builder[Request, Params, Event]) WithErrors source
func (b Builder[Request, Params, Event]) WithErrors(errs ...problem.ErrorStatus) Builder[Request, Params, Event]WithErrors maps the operation's declared errors, and errors from the wire request's Params method, to problems. They're matched in order.
(Builder[Request, Params, Event]) WithKeepAlive source
func (b Builder[Request, Params, Event]) WithKeepAlive(d time.Duration) Builder[Request, Params, Event]WithKeepAlive sets how long the stream may be idle before the handler sends a keep-alive comment.
(Builder[Request, Params, Event]) WithWriteTimeout source
func (b Builder[Request, Params, Event]) WithWriteTimeout(d time.Duration) Builder[Request, Params, Event]WithWriteTimeout sets how long each write may take. The handler extends the connection's write deadline by this much before every write, so the server's write timeout doesn't end the stream.