-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
57 lines (47 loc) · 1.03 KB
/
main.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
package main
import (
"fmt"
"log"
"net/http"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
var clients []*websocket.Conn = []*websocket.Conn{}
func ws(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
clients = append(clients, c)
}
func main() {
ticker := time.NewTicker(time.Second)
var count int64 = 0
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/ws", ws)
http.HandleFunc("/dstat", func(rw http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&count, 1)
rw.WriteHeader(http.StatusOK)
})
go func() {
for {
<-ticker.C
for i, c := range clients {
err := c.WriteMessage(websocket.TextMessage, []byte(fmt.Sprint(count)))
if err != nil {
c.Close()
clients = append(clients[:i], clients[i+1:]...)
}
}
count = 0
}
}()
err := http.ListenAndServe("localhost:8080", nil)
if err != nil {
log.Fatal(err)
}
}