forked from maxsupermanhd/WebChunk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.go
63 lines (59 loc) · 1.25 KB
/
ws.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
package main
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
var tasksProgressBroadcaster = NewBroadcaster()
func WSstatusHandler(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{
HandshakeTimeout: 2 * time.Second,
ReadBufferSize: 0,
WriteBufferSize: 0,
WriteBufferPool: nil,
Subprotocols: nil,
Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) {
log.Printf("Websocket error: %v %v", status, reason.Error())
},
CheckOrigin: func(r *http.Request) bool {
return true
},
EnableCompression: true,
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("Websocket upgrade error:", err)
return
}
defer c.Close()
errChan := make(chan error)
go func() {
for {
_, _, err := c.ReadMessage()
if err != nil {
errChan <- err
return
}
}
}()
msgc := tasksProgressBroadcaster.Subscribe()
defer tasksProgressBroadcaster.Unsubscribe(msgc)
for {
select {
case m := <-msgc:
b, err := json.Marshal(m)
if err != nil {
log.Printf("Failed to marshal progress: %v\n", err)
return
}
err = c.WriteMessage(websocket.TextMessage, b)
if err != nil {
return
}
case <-errChan:
return
}
}
}