README

sse

build-img pkg-img reportcard-img coverage-img

Server-Sent Events (SSE) library for Go.

See https://www.w3.org/TR/eventsource for the technical specification.

Features

  • Simple API.
  • Performant.
  • Dependency-free.
  • Low-level API to build a server.

Install

Go version 1.13

go get github.com/cristalhq/sse

Example

As a simple HTTP handler:

http.HandleFunc("/sse", func(w http.ResponseWriter, r *http.Request) {
    stream, err := sse.UpgradeHTTP(r, w)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    data := struct {
        Text string `json:"text"`
    }{
        Text: "hey there",
    }
    stream.WriteJSON("123", "msg", data)
})

See example_test.go for more.

Documentation

See these docs.

License

MIT License.

Documentation

Index

Constants

View Source
const (
	ErrNotFlusher  = Error("sse: not an HTTP-flusher")
	ErrNotHijacker = Error("sse: not an HTTP-hijacker")
)

Variables

This section is empty.

Functions

func LastEventID

func LastEventID(r *http.Request) string

LastEventID returns a last ID known by user. If it's not presented - empty string will be returnes

Types

type BinaryMarshaler

type BinaryMarshaler interface {
	MarshalBinary() ([]byte, error)
}

type Error

type Error string

func (Error) Error

func (e Error) Error() string

type Stream

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

func UpgradeHTTP

func UpgradeHTTP(r *http.Request, w http.ResponseWriter) (*Stream, error)

func (*Stream) Close

func (s *Stream) Close() error

Close sends close event with empth data.

func (*Stream) Flush

func (s *Stream) Flush() error

func (*Stream) SetEvent

func (s *Stream) SetEvent(event string) error

func (*Stream) SetID

func (s *Stream) SetID(id int64) error

func (*Stream) SetRetry

func (s *Stream) SetRetry(retry time.Duration) error

func (*Stream) WriteBinary

func (s *Stream) WriteBinary(message BinaryMarshaler) error

func (*Stream) WriteBytes

func (s *Stream) WriteBytes(data []byte) error

func (*Stream) WriteEvent

func (s *Stream) WriteEvent(id int64, event string, data []byte) error

func (*Stream) WriteFloat

func (s *Stream) WriteFloat(num float64) error

func (*Stream) WriteInt

func (s *Stream) WriteInt(num int64) error

func (*Stream) WriteJSON

func (s *Stream) WriteJSON(v interface{}) error

func (*Stream) WriteString

func (s *Stream) WriteString(data string) error

func (*Stream) WriteText

func (s *Stream) WriteText(message TextMarshaler) error

type TextMarshaler

type TextMarshaler interface {
	MarshalText() ([]byte, error)
}

type Upgrader

type Upgrader struct {
	Timeout time.Duration
}

func (Upgrader) Upgrade

func (u Upgrader) Upgrade(conn io.ReadWriter) (*Stream, error)

func (Upgrader) UpgradeHTTP

func (u Upgrader) UpgradeHTTP(r *http.Request, w http.ResponseWriter) (*Stream, error)