-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (72 loc) · 1.46 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"bytes"
"encoding/json"
"flag"
"log"
"net/url"
"os"
"os/signal"
"time"
"./lib"
"github.com/gorilla/websocket"
)
var addr = flag.String("addr", "localhost:8080", "monitoring address")
func main() {
var buf bytes.Buffer
flag.Parse()
log.SetFlags(0)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer c.Close()
defer close(done)
for {
_, _, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
}
}()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
d, err := lib.GetServerStat()
if err != nil {
log.Println("get status error:", err)
d.ErrorInfo = err
}
j, _ := json.Marshal(d)
buf.Write(j)
er := c.WriteMessage(websocket.TextMessage, j)
if er != nil {
log.Println("write:", er)
return
}
case <-interrupt:
log.Println("interrupt")
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
c.Close()
return
}
}
}