sse

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: May 21, 2023 License: MIT Imports: 11 Imported by: 2

README

go-sse

Build Status Coverage Status Go Report Card Go Reference MIT License

This package attempts to provide a robust and reliable implementation of server-sent events. One might use this package if they were writing an application that needed to connect to an SSE server endpoint and read events in a continuous stream or provide events to a front-end service.

Features

Here's what you get with this package:

  • Complete documentation for every last type and method in the package
  • Compliancy with section 9.2 of the WHATWG HTML specification
  • Extensive test suite to ensure conformance

go-sse requires a minimum of Go 1.18.

Basic Usage

To use the package in your application, begin by importing it:

import "github.com/lampctl/go-sse"

Use as a Client

Create a client using:

c, err := sse.NewClientFromURL("http://example.com/sse")
if err != nil {
    // ...
}

You can now read events directly from the c.Events channel as they are received:

for e := range c.Events {
    fmt.Println("Event received!")
    fmt.Println(e.Data)
}

Note that if the connection is closed or interrupted, the client will attempt to reconnect as per the spec and continue returning events from where it was interrupted. This is all handled behind the scenes and won't affect the status of the event channel.

When you are done receiving events, close the client:

c.Close()

Use as a Server

The server component is provided via Handler, which implements http.Handler:

h := sse.NewHandler(nil)

// ...or if you want to customize initialization:
h := sse.NewHandler(&sse.HandlerConfig{
    NumEventsToKeep:   10,
    ChannelBufferSize: 4,
})

To send an event, simply use the Send() method:

h.Send(&sse.Event{
    Type: "alert",
    Data: "The aliens are invading!",
    ID:   "12345",
})

When you are done, use the Close() method:

h.Close()

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultHandlerConfig = &HandlerConfig{
	NumEventsToKeep:   10,
	ChannelBufferSize: 4,
}

DefaultHandlerConfig provides a set of defaults.

Functions

This section is empty.

Types

type Client

type Client struct {

	// Events provides a stream of events from the server.
	Events <-chan *Event
	// contains filtered or unexported fields
}

Client connects to a server providing SSE. The client will continue to maintain the connection, resuming from the last event ID when disconnected.

func NewClient

func NewClient(req *http.Request, client *http.Client) *Client

NewClient creates a new SSE client from the provided parameters. If client is set to nil, http.DefaultClient will be used. The client will begin connecting to the server and continue sending events until an HTTP 204 is received or explicitly terminated with Close().

func NewClientFromURL

func NewClientFromURL(url string) (*Client, error)

NewClientFromURL creates a new SSE client for the provided URL and uses http.DefaultClient to send the requests.

func (*Client) Close

func (c *Client) Close()

Close disconnects and shuts down the client.

type Event

type Event struct {
	Type string
	Data string
	ID   string

	// Retry is only used when sending events, not receiving them.
	Retry time.Duration

	// UserData is useful for filtering events with FilterFn in HandlerConfig.
	UserData any
}

Event represents an individual event from the event stream.

func (*Event) Bytes added in v1.1.0

func (e *Event) Bytes() []byte

Bytes returns the byte representation of the event. Note that the result is only valid if Type, Data, and ID do NOT contain a CR or LF.

type Handler added in v1.1.0

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

Handler provides an http.Handler that can be used for sending events to any number of connected clients.

func NewHandler added in v1.1.0

func NewHandler(cfg *HandlerConfig) *Handler

NewHandler creates a new Handler instance.

func (*Handler) Close added in v1.1.0

func (h *Handler) Close()

Close shuts down all of the event channels and waits for them to complete.

func (*Handler) Send added in v1.1.0

func (h *Handler) Send(e *Event)

Send sends the provided event to all connected clients. Any clients that block are forcibly disconnected.

func (*Handler) ServeHTTP added in v1.1.0

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HandlerConfig added in v1.1.0

type HandlerConfig struct {

	// NumEventsToKeep indicates the number of events that should be kept for
	// clients reconnecting.
	NumEventsToKeep int

	// ChannelBufferSize indicates how many events should be buffered before
	// the connection is assumed to be dead.
	ChannelBufferSize int

	// ConnectedFn, if provided, is invoked when a client connects. The return
	// value of this function is associated with the client and is passed to
	// InitFn and FilterFn.
	ConnectedFn func(*http.Request) any

	// InitFn, if provided, is invoked right before a client enters the event
	// loop and sends any events that it returns to the client. This is useful,
	// for example, if you are synchronizing application state. The single
	// parameter is equal to the value returned by ConnectedFn.
	InitFn func(any) []*Event

	// FilterFn, if provided, is invoked when an event is being sent to a
	// client to determine if it should actually be sent. The first parameter
	// is equal to the value returned by ConnectedFn and the return value
	// should be set to true to send the event.
	FilterFn func(any, *Event) bool
}

HandlerConfig provides a means of passing configuration to NewHandler.

type Reader

type Reader struct {

	// LastEventID maintains the ID of the last event received. If the last
	// event did not contain an ID, then the value from the previous event is
	// used. If no event with an ID has been received, this will be set to the
	// zero value.
	LastEventID string

	// ReconnectionTime indicates how long the client should wait (in MS)
	// before attempting to reconnect to the server. Note that this is set to
	// the zero value unless the server changes it and a sensible default
	// should be selected in place of the zero value.
	ReconnectionTime int
	// contains filtered or unexported fields
}

Reader reads events from an io.Reader.

func NewReader

func NewReader(r io.Reader) *Reader

NewReader creates a new Reader instance for the provided io.Reader.

func (*Reader) NextEvent

func (r *Reader) NextEvent() (*Event, error)

NextEvent blocks until the next event is received, there are no more events, or an error occurs. No event or error will be returned if there are no more events.

Jump to

Keyboard shortcuts

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