This repository has been archived by the owner on Mar 4, 2022. It is now read-only.
forked from 256dpi/handlauf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
72 lines (61 loc) · 1.42 KB
/
stream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"net/http"
"strconv"
"sync"
"sync/atomic"
"github.com/gorilla/websocket"
)
var clients sync.Map
var numClients int64
var server *http.Server
func stream(addr string) {
// prepare upgrader
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// prepare handler
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// perform upgrade
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Printf("stream: %s\n", err.Error())
return
}
// add client
fmt.Printf("stream: added client %s\n", conn.RemoteAddr().String())
clients.Store(conn, nil)
atomic.AddInt64(&numClients, 1)
})
// run server
server = &http.Server{Addr: addr, Handler: handler}
panic(server.ListenAndServe())
}
func emit(values sample) {
// build payload
payload := make([]byte, 0, 256)
for i, v := range values {
if i > 0 {
payload = append(payload, ',')
}
payload = strconv.AppendFloat(payload, v, 'f', 2, 64)
}
// broadcast
clients.Range(func(key, _ interface{}) bool {
// get conn
conn := key.(*websocket.Conn)
// write message
err := conn.WriteMessage(websocket.TextMessage, payload)
if err != nil {
fmt.Printf("emit: %s\n", err.Error())
_ = conn.Close()
clients.Delete(key)
atomic.AddInt64(&numClients, -1)
fmt.Printf("emit: removed client %s", conn.RemoteAddr().String())
}
return true
})
}