-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
108 lines (99 loc) · 2.42 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
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
104
105
106
107
108
package main
import (
"fmt"
"log"
"net/http"
"path/filepath"
"github.com/gobuffalo/packr/v2"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{} // use default options
var clients = make(map[*websocket.Conn]bool)
var router *mux.Router
func echo(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}
}
func ws(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade: ", err)
return
}
log.Println("Websocket client connected")
defer c.Close()
clients[c] = true
UpdateScoreBoard(&s)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
}
}
func UpdateScoreBoard(s *Scoreboard) {
for client := range clients {
err := client.WriteJSON(s)
if err != nil {
log.Printf("Websocket error: %s", err)
client.Close()
delete(clients, client)
}
}
}
func UpdateTimer(function string) {
for client := range clients {
message := []byte(function)
err := client.WriteMessage(websocket.TextMessage, message)
if err != nil {
log.Printf("Websocket error: %s", err)
client.Close()
delete(clients, client)
}
}
}
func StartHTTPServer() {
r := mux.NewRouter()
r.HandleFunc("/ws", ws)
r.HandleFunc("/echo", echo)
r.Handle("/logo", http.FileServer(http.Dir(logoPath)))
// box := packr.New("static", "./static")
// r.Handle("/", http.FileServer(box))
router = r
go func() {
log.Fatal(http.ListenAndServe(":8080", r))
}()
fmt.Println("Starting HTTP Server @ http://localhost:8080")
}
func UpdateStaticRoute() {
defaultTheme := packr.New("static", "./static")
bglTheme := packr.New("bgl", "./themes/bgl")
switch selectedTheme {
case "default":
router.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(defaultTheme)))
case "bgl":
router.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(bglTheme)))
default:
router.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir(filepath.Join(themePath, selectedTheme)))))
}
}