-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
103 lines (91 loc) · 2.31 KB
/
server.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write git objects to client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 10 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Poll git repo for changes with this period.
repoPeriod = 3 * time.Second
// message client sends to get objects even if no changes occurred
needObjects = "need-objects"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
func getObjectsIfChange(repo *Repo) []byte {
if repo.changed() {
log.Printf("Repo changed. Refreshing data...")
repo.refresh()
return repo.toJson()
}
return nil
}
func reader(ws *websocket.Conn) {
defer ws.Close()
ws.SetReadLimit(512)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, msg, err := ws.ReadMessage()
if err != nil {
break
}
if string(msg) == needObjects {
log.Printf("objects from %s requested from client ...\n", repo.location)
objects := repo.toJson()
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.TextMessage, objects); err != nil {
return
}
log.Println("objects sent to client.")
}
}
}
func writer(ws *websocket.Conn) {
pingTicker := time.NewTicker(pingPeriod)
repoTicker := time.NewTicker(repoPeriod)
defer func() {
pingTicker.Stop()
repoTicker.Stop()
ws.Close()
}()
for {
select {
case <-repoTicker.C:
var objects []byte = nil
objects = getObjectsIfChange(repo)
if objects != nil {
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.TextMessage, objects); err != nil {
return
}
}
case <-pingTicker.C:
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
func serveWs(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Println(err)
}
return
}
go writer(ws)
reader(ws)
}