Server-Sent Events for Go
This project is fork of go-sse. The defferences are: possibility to send message to specified client, Client disconnect callback and possibility to set not a standard logger, specifying protocol version (message will be send only to clients with version not lower than message's version)
Server-sent events is a method of continuously sending data from a server to the browser, rather than repeatedly requesting it, replacing the "long polling way".
It's supported by all major browsers and for IE/Edge you can use a polyfill.
go-sse
is a small library to create a Server-Sent Events server in Go.
- Multiple channels (isolated)
- Broadcast message to all channels
- Individual message to specified client
- Naming of clients
- Client's protocol version
- Custom headers (useful for CORS)
Last-Event-ID
support (resend lost messages)- Follow SSE specification
Simple Go example that handle 2 channels and send messages to all clients connected in each channel.
package main
import (
"log"
"net/http"
"strconv"
"time"
"github.com/alexandrevicenzi/go-sse"
)
func main() {
// Create the server.
s := sse.NewServer(nil)
defer s.Shutdown()
// Register with /events endpoint.
http.Handle("/events/", s)
// Dispatch messages to channel-1.
go func () {
for {
s.SendMessage("/events/channel-1", sse.SimpleMessage(time.Now().String()))
time.Sleep(5 * time.Second)
}
}()
// Dispatch messages to channel-2
go func () {
i := 0
for {
i++
s.SendMessage("/events/channel-2", sse.SimpleMessage(strconv.Itoa(i)))
time.Sleep(5 * time.Second)
}
}()
http.ListenAndServe(":3000", nil)
}
Connecting to our server from JavaScript:
e1 = new EventSource('/events/channel-1');
e1.onmessage = function(event) {
// do something...
};
e2 = new EventSource('/events/channel-2');
e2.onmessage = function(event) {
// do something...
};