-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
67 lines (59 loc) · 1.11 KB
/
websocket.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
package main
import (
"net/http"
"time"
"github.com/gorilla/websocket"
)
var event = struct {
Type Type
Error string
Data interface{}
Time string
}{ //Default values:
Type: UNKNOWN,
}
type Type int
const (
UNKNOWN Type = iota
KEY_EVENT
CONFIG_WROTE
CONFIG_DELETE
)
func setEvent(Type Type, err string, data interface{}) {
new := event
new.Type = Type
new.Error = err
new.Data = data
new.Time = time.Now().Format(time.RFC3339)
event = new
}
var upgrader = websocket.Upgrader{
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { //always anser request no matter what the origin is
return true //always return true, so that every request is allowed
},
}
func handleWebsocket(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logErr(err)
return
}
defer c.Close()
//store the last event that happended
last := event
for {
time.Sleep(1 * time.Millisecond)
if last != event {
err = c.WriteJSON(event)
if err != nil {
if websocket.IsCloseError(err) {
break
}
logErr(err)
break
}
}
last = event
}
}