sse

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package sse writes Server-Sent Events, the text/event-stream bodies of the WHATWG HTML standard, for replies: their model, the checks of the model, and the stream that sends them one by one, with their delays.

Index

Constants

This section is empty.

Variables

View Source
var EventSchema = config.NewSchema(
	eventField{
		Key: "event", Kind: config.String, Usage: "Event type. Clients dispatch an event without one as a message.",
		Set: func(e *EventSpec, v config.Value) error { e.Event = v.Str; return nil },
	},
	eventField{
		Key: "id", Kind: config.String, Usage: "Event id, which clients send back as Last-Event-ID. An empty id resets it.",
		Set: func(e *EventSpec, v config.Value) error { e.ID, e.HasID = v.Str, true; return nil },
	},
	eventField{
		Key: "data", Kind: config.Any, Usage: "Data of the event: text as is, anything else as JSON. A data line per line.",
		Set: func(e *EventSpec, v config.Value) error {
			switch x := v.Any.(type) {
			case nil:
				return config.Invalid(v, v.Key+" is null", `remove it, write "" for empty data, or data_json: null for JSON null`)
			case string:
				e.Data, e.DataKind = []byte(x), DataText
			default:
				b, err := json.Marshal(x, json.Deterministic(true))
				if err != nil {
					return err
				}

				e.Data, e.DataKind = b, DataJSON
			}

			e.HasData = true

			return nil
		},
	},
	eventField{
		Key: "data_json", Kind: config.Any,
		Usage: "Data of the event as JSON, strings and null too, never a template. In place of data.",
		Set: func(e *EventSpec, v config.Value) error {
			b, err := json.Marshal(v.Any, json.Deterministic(true))
			if err != nil {
				return err
			}

			e.Data, e.DataKind, e.HasData = b, DataJSON, true

			return nil
		},
	},
	eventField{
		Key: "retry", Kind: config.Duration,
		Usage: "Reconnection time from this event on: milliseconds or a Go duration (1.5s).",
		Set:   func(e *EventSpec, v config.Value) error { e.Retry, e.HasRetry = v.Dur, true; return nil },
	},
	eventField{
		Key: "comment", Kind: config.String, Usage: "Comment sent first, a comment line per line, which clients skip.",
		Set: func(e *EventSpec, v config.Value) error { e.Comment = v.Str; return nil },
	},
	eventField{
		Key: "delay", Kind: config.Duration,
		Usage: "How long to wait before the event, in place of event_delay: milliseconds or a Go duration (1.5s).",
		Set:   func(e *EventSpec, v config.Value) error { e.Delay, e.HasDelay = v.Dur, true; return nil },
	},
	eventField{
		Key: "raw", Kind: config.String, Usage: "Text sent as it is, in place of the other fields, such as CRLF line endings.",
		Set: func(e *EventSpec, v config.Value) error { e.Raw, e.HasRaw = []byte(v.Str), true; return nil },
	},
)

EventSchema decodes an event of an event_stream object.

View Source
var SpecSchema = config.NewSchema(
	specField{
		Key: "events", Kind: config.Any, Usage: "Events of the stream, in order.",
		Set: func(s *Spec, v config.Value) error {

			return config.Items(v, func(item config.Value) error {
				ev, err := decodeEvent(item)
				s.Events = append(s.Events, ev)

				return err
			})
		},
	},
	specField{
		Key: "retry", Kind: config.Duration,
		Usage: "Reconnection time sent first, which clients read in whole milliseconds: milliseconds or a Go duration (1.5s).",
		Set:   func(s *Spec, v config.Value) error { s.Retry, s.HasRetry = v.Dur, true; return nil },
	},
	specField{
		Key: "event_delay", Kind: config.Any,
		Usage: "Wait before each event without a delay of its own: milliseconds, a Go duration (1.5s), or a typed delay distribution.",
		Set: func(s *Spec, v config.Value) error {
			var err error
			s.EventDelay, err = delay.Decode(v)
			return err
		},
	},
	specField{
		Key: "heartbeat", Kind: config.Duration,
		Usage: "Send a comment each time the stream waits this long without sending anything: milliseconds or a Go duration (1.5s).",
		Set:   func(s *Spec, v config.Value) error { s.Heartbeat = v.Dur; return nil },
	},
	specField{
		Key: "keep_open", Kind: config.Bool, Usage: "Keep the stream open after its last event, until the client leaves.",
		Set: func(s *Spec, v config.Value) error { s.KeepOpen = v.Bool; return nil },
	},
	specField{
		Key: "resume", Kind: config.Bool, Usage: "Send a request with a Last-Event-ID only the events after the one with that id.",
		Set: func(s *Spec, v config.Value) error { s.Resume = v.Bool; return nil },
	},
)

SpecSchema decodes the event_stream object of a mock file, as response.event_stream writes it. EventSchema decodes each of its events.

Functions

This section is empty.

Types

type DataKind

type DataKind int

DataKind says what the data of an event is.

const (
	DataText DataKind = iota // text, a template when the spec is templated
	DataJSON                 // JSON, written as it is
)

type Encoder

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

Encoder renders the events of a Spec. It is safe for concurrent use.

func Compile

func Compile(s *Spec, engine vlatte.TemplateEngine) (*Encoder, error)

Compile checks s and compiles its templates with engine. The Encoder copies s: changing s afterwards doesn't change it.

When s is templated, the event types, ids, comments and text data are templates. JSON data and raw events are sent as they are. engine can be nil when s isn't templated.

func (*Encoder) Encode

func (e *Encoder) Encode(data any) ([]Frame, error)

Encode renders the events with data for their templates.

func (*Encoder) Stream

func (e *Encoder) Stream(ctx context.Context, data any, lastEventID string) (*Stream, error)

Stream renders the events with data and returns the stream that sends them, until ctx ends. lastEventID is the Last-Event-ID of the request, "" when it has none: a resuming stream starts after the event with that id, or at the first when none has it.

type EventSpec

type EventSpec struct {
	Event    string // the event type
	ID       string
	HasID    bool // an empty ID is sent too: it resets the last event ID of the client
	Data     []byte
	DataKind DataKind
	HasData  bool
	Retry    time.Duration
	HasRetry bool
	Comment  string
	Raw      []byte        // sent as it is, for what the fields can't write, such as CRLF line endings
	HasRaw   bool          // Raw excludes the fields
	Delay    time.Duration // the wait before the event, in place of the stream's EventDelay
	HasDelay bool
	Err      error // what went wrong building the event, such as JSON data that doesn't marshal
}

EventSpec is an event of a stream: its fields, or Raw bytes in their place.

type Frame

type Frame struct {
	Bytes    []byte
	ID       string // the id of the event, when HasID is set
	HasID    bool
	Delay    time.Duration // the wait before the event, when HasDelay is set
	HasDelay bool
}

Frame is an event as it goes on the wire, with the wait before it.

type Spec

type Spec struct {
	Events     []*EventSpec
	Retry      time.Duration // the reconnection time sent first, when HasRetry is set
	HasRetry   bool
	EventDelay vlatte.Delay  // picks the wait before each event that has no delay of its own; nil waits for none
	Heartbeat  time.Duration // sends a comment after this long without a write; 0 sends none
	KeepOpen   bool          // the stream stays open after the last event, until the client leaves
	Resume     bool          // a request with a Last-Event-ID gets the events after the one with that id
	Templated  bool          // the text of the events is templates: see Compile
}

Spec is an event stream to send.

func Decode

func Decode(v config.Value) (*Spec, error)

Decode decodes the event_stream object v of a mock file. Every problem is keyed under v.Key, as response.event_stream.events[1].raw. With problems, the spec is what decoded; it is nil when v isn't an object. Text that is a template, once the reply makes the stream templated, is checked by Compile.

func (*Spec) Check

func (s *Spec) Check() error

Check returns what makes s a stream that can't be sent as asked, all of it joined, or nil.

func (*Spec) Doc

func (s *Spec) Doc() map[string]any

Doc returns s as a mock file writes it, including any failure to describe its delay.

type Stream

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

Stream reads an event stream as it is sent: each Read returns the next event, or a heartbeat, once its wait is over. It ends with io.EOF after the last event, or, when the stream keeps open, once its context ends. A context that ends, as when the client leaves, ends it with io.EOF too: the client got every event it read.

func (*Stream) Close

func (s *Stream) Close() error

Close ends the stream: a Read after it returns io.EOF.

func (*Stream) Read

func (s *Stream) Read(p []byte) (int, error)

Read implements io.Reader. It blocks until the next event or heartbeat is due. A delay evaluation failure is returned to the reader; cancellation retains the stream's EOF behavior.

Jump to

Keyboard shortcuts

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