Server-Sent Events in Go

Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection.

The chat and the charts data is provided in realtime using the SSE implemention of Gin Framework.

Nick Message
{{if .nick}}
{{.nick}}
{{end}}
{{if .nick}}

Inbound/Outbound

{{else}}
Join the SSE real-time chat
{{end}}

Realtime server Go stats

Number of Goroutines

HEAP/Stack bytes

Mallocs/Frees

Source code

Server-side (Go)

func streamRoom(c *gin.Context) {
    roomid := c.ParamValue("roomid")
    listener := openListener(roomid)
    statsTicker := time.NewTicker(1 * time.Second)
    defer closeListener(roomid, listener)
    defer statsTicker.Stop()

    c.Stream(func(w io.Writer) bool {
        select {
        case msg := <-listener:
            c.SSEvent("message", msg)
        case <-statsTicker.C:
            c.SSEvent("stats", Stats())
        }
        return true
    })
}

Client-side (JS)

function StartSSE(roomid) {
    var source = new EventSource('/stream/'+roomid);
    source.addEventListener('message', newChatMessage, false);
    source.addEventListener('stats', stats, false);
}