Server-Sent Events. Room "{{.roomid}}"

# Server-Sent Events in Go

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

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

Nick | Message
--- | ---

{{if .nick}}
Message
{{.nick}}
{{else}} Join the SSE real-time chat
{{end}}

◼︎ Users
◼︎ Inbound messages / sec
◼︎ Outbound messages / sec

## Realtime server Go stats

### Memory usage

◼︎ Heap bytes
◼︎ Stack bytes

### Allocations per second

◼︎ Mallocs / sec
◼︎ Frees / sec

## MIT Open Sourced

- This demo website (JS and Go)
- The SSE implementation in Go
- The Web Framework (Gin)

### 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);
    }

### SSE package

    import "github.com/manucorporat/sse"

    func httpHandler(w http.ResponseWriter, req *http.Request) {
        // data can be a primitive like a string, an integer or a float
        sse.Encode(w, sse.Event{
            Event: "message",
            Data:  "some data\nmore data",
        })

        // also a complex type, like a map, a struct or a slice
        sse.Encode(w, sse.Event{
            Id:    "124",
            Event: "message",
            Data: map[string]interface{}{
                "user":    "manu",
                "date":    time.Now().Unix(),
                "content": "hi!",
            },
        })
    }

    event: message
    data: some data\\nmore data

    id: 124
    event: message
    data: {"content":"hi!","date":1431540810,"user":"manu"}