The package provides fast primitives to manipulate Server-Sent Events as defined by the HTML5 spec.
Get the package with go get github.com/alevinval/sse
Check the contributing guidelines when submitting changes.
import "github.com/alevinval/sse/pkg/eventsource"
es, err := eventsource.New("http://foo.com/stocks/AAPL")
for {
select {
case event := <-es.MessageEvents():
log.Printf("[Event] ID: %s\n Name: %s\n Data: %s\n\n", event.ID, event.Name, event.Data)
case state := <-es.ReadyState():
log.Printf("[ReadyState] %s (err=%v)", state.ReadyState, err)
}
}
The library includes WithBasicAuth
and WithAuthorizationBearer
modifiers.
eventsource.New("http://foo.com/stocks/AAPL", eventsource.WithBasicAuth("user", "password"))
eventsource.New("http://foo.com/stocks/AAPL", eventsource.WithAuthorizationBearer("token"))
Create your own RequestModifier
in case you need further manipulation of the
underlying HTTP request.
The decoder package allows decoding events from any io.Reader
source
import "github.com/alevinval/sse/pkg/decoder"
resp, _ := http.Get("http://foo.com/stocks/AAPL")
decoder = decoder.New(resp.Body) // any io.Reader works
for {
event, err := decoder.Decode()
}
The encoder package allows encoding a stream of events
import "github.com/alevinval/sse/pkg/encoder"
event := &base.MessageEvent{
ID: "some id",
Name: "stock-update",
Data: "AAPL 30.09",
}
out := new(bytes.Buffer)
encoder := New(out)
encoder.WriteComment("example event")
encoder.WriteEvent(event)