sse

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2020 License: MIT Imports: 9 Imported by: 2

README

Server-sent events for Go

GoDoc

This is a lightweight SEE client and server library for Golang which is designed to play nicely along different packages and provide a convient usage. This package uses the context package and thus requires Go 1.7 or later.

Client usage

import (
	"github.com/longsleep/sse"
)
var DefaultClient = &http.Client{}

DefaultClient is the default client used for requests.

var (
	//ErrNilChan will be returned by Notify if it is passed a nil channel
	ErrNilChan = fmt.Errorf("nil channel given")
)
var DefaultGetReq = func(verb, uri string, body io.Reader) (*http.Request, error) {
	return http.NewRequest(verb, uri, body)
}

GetReq is a function to return a single request. It will be used by notify to get a request and can be replaces if additional configuration is desired on the request. The "Accept" header will necessarily be overwritten.

func Notify(uri string, client *http.Client, getReq func(verb, uri string, body io.Reader) (*http.Request, error), evCh chan<- *Event) error

Notify takes the uri of an SSE stream, http.Client, request generator function // and a channel and will send an Event down the channel when recieved, until // the stream is closed. This is blocking, and so you will likely want to call // this in a new goroutine (via go Notify(..)). If client or getReq ire nil, // the DefaultClient and DefaultGetReq values are used.

type Event
type Event struct {
	URI  string
	Type string
	Data io.Reader
}

Event is a go representation of an http server-sent event

Server Examples

Note: Also look into the examples folder.

import (
	"net/http"
	"github.com/longsleep/sse"
)

type Person struct {
	Name string
	Age int
}

func main() {

	http.HandleFunc("/event", func(w http.ResponseWriter, r *http.Request) {
		// get a SSE connection from the HTTP request
		// in a real world situation, you should look for the error (second return value)
		conn, _ := sse.Upgrade(w, r)

		// writes the struct as JSON
		conn.WriteJson(&Person{
			Name: "Jan",
			Age: 17,
		})

		// writes the struct as XML
		conn.WriteXml(&Person{
			Name: "Ernst",
			Age: 23,
		})

		// write a plain string
		conn.WriteString("Hello how are you?")

		// trigger the event "feed" with "This is a message" as payload
		// [extended example](https://github.com/longsleep/sse/tree/master/examples/events)
		conn.WriteStringEvent("feed", "This is a message")

		for {
			// keep this goroutine alive to keep the connection

			// get a message from some channel
			// blocks until it recieves a messages and then instantly sends it to the client
			msg := <-someChannel
			conn.WriteString(msg)
		}
	})

	http.ListenAndService(":80", nil)
}

Usage with a Upgrader instance

Using a Upgrader instance allows you to specify a RetryTime interval at which the client will attempt to reconnect to the EventSource.

import (
	"net/http"
	"github.com/longsleep/sse"
)

type Person struct {
	Name string
	Age int
}

func main() {

	upgrader := sse.Upgrader{
		RetryTime: 5 * time.Second,
	}

	http.HandleFunc("/event", func(w http.ResponseWriter, r *http.Request) {
		// get a SSE connection from the HTTP request
		// in a real world situation, you should look for the error (second return value)
		conn, _ := upgrader.Upgrade(w, r)

		// writes the struct as JSON
		conn.WriteJson(&Person{
			Name: "Jan",
			Age: 17,
		})

		for {
			// get a message from some channel
			// blocks until it recieves a messages and then instantly sends it to the client
			msg := <-someChannel
			conn.WriteString(msg)
		}
	})

	http.ListenAndService(":80", nil)
}

Acknowledgements

This project is a combination of two see libraries:

Thank you!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrStreamingNotSupported = errors.New("streaming unsupported")
	ErrConnectionClosed      = errors.New("connection already closed")
)
View Source
var DefaultClient = &http.Client{}

Client is the default client used for requests.

View Source
var DefaultGetReq = func(method, uri string, body io.Reader) (*http.Request, error) {
	return http.NewRequest(method, uri, body)
}

DefaultGetReq is a function to return a single request. It will be used by notify to get a request and can be replaced if additional configuration is desired on the request. The "Accept" header will necessarily be overwritten.

View Source
var (
	// ErrNilChan will be returned by Notify if it is passed a nil channel
	ErrNilChan = fmt.Errorf("nil channel given")
)

Functions

func Notify added in v1.1.0

func Notify(uri string, client *http.Client, getReq getReqFunc, evCh chan<- *Event) error

Notify takes the uri of an SSE stream, http.Client, request generator function and a channel, and will send an Event down the channel when recieved, until the stream is closed. This is blocking, and so you will likely want to call this

in a new goroutine (via `go Notify(..)`). If client or getReq ire nil, the

DefaultClient and DefaultGetReq values are used.

Types

type Conn

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

func Upgrade

func Upgrade(w http.ResponseWriter, r *http.Request) (*Conn, error)

Global Upgrade for method for usage without a Upgrader instance. Refer to Upgrader.Upgrade for complete documentation.

func (*Conn) Close

func (c *Conn) Close()

Forces the connection to close. The Conn object should not be used anymore.

func (*Conn) IsOpen

func (c *Conn) IsOpen() bool

Returns whether the connection is still opened.

func (*Conn) Write

func (c *Conn) Write(msg []byte) error

Sends a byte-slice to the connected client. Returns an error if the connection is already closed.

func (*Conn) WriteEvent

func (c *Conn) WriteEvent(typ string, msg []byte) error

Sends a byte-slice to the connected client and triggers the specified event with the data. Returns an error if the connection is already closed.

func (*Conn) WriteEventWithID

func (c *Conn) WriteEventWithID(id, typ string, msg []byte) error

Sends a byte-slice to the connected client and triggers the specified event with the data. Returns an error if the connection is already closed.

func (*Conn) WriteJson

func (c *Conn) WriteJson(value interface{}) error

Sends a json-encoded struct to the connected client. Returns an error if the connection is already closed or if the encoding failed.

func (*Conn) WriteJsonEvent

func (c *Conn) WriteJsonEvent(typ string, value interface{}) error

Sends a json-encoded struct to the connected client, targeting the specified event. Returns an error if the connection is already closed or if the encoding failed.

func (*Conn) WriteString

func (c *Conn) WriteString(msg string) error

Sends a string to the connected client. Returns an error if the connection is already closed.

func (*Conn) WriteStringEvent

func (c *Conn) WriteStringEvent(typ, msg string) error

Sends a string to the connected client, targeting the specified event. Returns an error if the connection is already closed.

func (*Conn) WriteXml

func (c *Conn) WriteXml(value interface{}) error

Sends a xml-encoded struct to the connected client. Returns an error if the connection is already closed or if the encoding failed.

func (*Conn) WriteXmlEvent

func (c *Conn) WriteXmlEvent(typ string, value interface{}) error

Sends a xml-encoded struct to the connected client, targeting the specified event. Returns an error if the connection is already closed or if the encoding failed.

type Event added in v1.1.0

type Event struct {
	URI string

	Type string
	ID   string
	Data io.Reader
}

Event is a go representation of an http server-sent event

type Upgrader

type Upgrader struct {
	// time between two connects from a client
	RetryTime time.Duration
}

func (Upgrader) Upgrade

func (up Upgrader) Upgrade(w http.ResponseWriter, r *http.Request) (*Conn, error)

Takes over a HTTP-connection and returns a SSE-Connection, which can be used to send events. Returns an error, if the connection does not support streaming. Please note, that in this case the client will also be notified and the HTTP-connection should therefore not be used anymore.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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