-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
410 lines (336 loc) · 9.56 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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"strconv"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
const (
gameCodeMin = 100000
gameCodeMax = 999999
)
type player struct {
GameID int
PlayerID int
Name string
}
type message struct {
GameID int `json:"gameID,omitempty"`
PlayerID int `json:"playerID,omitempty"`
Action string `json:"action,omitempty"`
}
var games map[int][](chan message)
var players map[int]player
var hosts map[int]chan message
var serverCh chan message
var hostCh chan message
func init() {
rand.Seed(time.Now().Unix())
games = map[int][](chan message){}
players = map[int]player{}
hosts = map[int]chan message{}
serverCh = make(chan message)
hostCh = make(chan message)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/api/host", HostCreateHandler).Methods("POST")
r.HandleFunc("/api/host/{id}", HostListenHandler).Methods("GET")
r.HandleFunc("/api/host/{id}/reset", HostResetHandler).Methods("POST")
r.HandleFunc("/api/host/{id}/lock", HostLockHandler).Methods("POST")
r.HandleFunc("/api/play/{id}", PlayHandler).Methods("GET")
r.HandleFunc("/api/play/{id}/buzz", BuzzHandler).Methods("POST")
r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("./build"))))
corsH := handlers.CORS(handlers.AllowedOrigins([]string{"*"}))
go func() {
if os.Getenv("MODE") == "dev" {
fmt.Println("dev mode. using self-signed cert")
log.Fatal(http.ListenAndServeTLS(":8080", "local.crt", "local.key", corsH(r)))
} else {
log.Fatal(http.ListenAndServeTLS(":8080", "fullchain.pem", "privkey.pem", corsH(r)))
}
}()
// broadcast to clients
go func() {
// select from the server channel forever
// when a message comes in, grab it's game ID, and grab the client channels
// for the given game id
for {
select {
case msg := <-serverCh:
log.Printf("client msg received: %v", msg)
for _, clientCh := range games[msg.GameID] {
clientCh <- msg
}
if msg.Action == "disconnect" {
delete(hosts, msg.GameID)
delete(games, msg.GameID)
log.Println("game ended")
}
}
}
}()
// broadcast to hosts
go func() {
for {
select {
case msg := <-hostCh:
log.Printf("host msg received: %v", msg)
hosts[msg.GameID] <- msg
}
}
}()
select {}
}
// IndexHandler returns a static status 200 to verify server is running
func IndexHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
w.WriteHeader(http.StatusOK)
}
// BuzzHandler returns a static status 200 to verify server is running
func BuzzHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
log.Println("buzz detected")
var clientMsg message
err := json.NewDecoder(r.Body).Decode(&clientMsg)
if err != nil {
log.Fatal("failed to encode json message", err.Error())
}
log.Printf("%v", clientMsg)
serverCh <- clientMsg
hostCh <- clientMsg
w.WriteHeader(http.StatusCreated)
}
func HostLockHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
// grab the game id from the path
params := mux.Vars(r)
id, ok := params["id"]
if !ok {
http.Error(w, "no 'id' found in URL", http.StatusBadRequest)
return
}
// convert to an int
i, err := strconv.Atoi(id)
if err != nil {
log.Println(err.Error())
http.Error(w, fmt.Sprintf("failed to convert game id [%s] to int", id), http.StatusInternalServerError)
return
}
lockToggleMsg := message{
GameID: i,
Action: "lock",
}
serverCh <- lockToggleMsg
w.WriteHeader(http.StatusCreated)
}
func HostResetHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
// grab the game id from the path
params := mux.Vars(r)
id, ok := params["id"]
if !ok {
http.Error(w, "no 'id' found in URL", http.StatusBadRequest)
return
}
// convert to an int
i, err := strconv.Atoi(id)
if err != nil {
log.Println(err.Error())
http.Error(w, fmt.Sprintf("failed to convert game id [%s] to int", id), http.StatusInternalServerError)
return
}
resetMsg := message{
GameID: i,
Action: "reset",
}
serverCh <- resetMsg
w.WriteHeader(http.StatusCreated)
}
// HostCreateHandler handles a simple POST request to create a game instance
// and returns a game code.
func HostCreateHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
gameCode := rand.Intn(gameCodeMax-gameCodeMin) + gameCodeMin
if _, ok := games[gameCode]; ok {
http.Error(w, "random game code collision. do a better job!", http.StatusInternalServerError)
return
}
games[gameCode] = []chan message{}
hosts[gameCode] = make(chan message)
log.Printf("creating game: %d", gameCode)
w.WriteHeader(http.StatusCreated)
err := json.NewEncoder(w).Encode(map[string]int{"gameCode": gameCode})
if err != nil {
http.Error(w, "failed to encode JSON response", http.StatusInternalServerError)
return
}
}
// PlayHandler establishes a stream and sends SSE to the client with
// game updates.
func PlayHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
notify := w.(http.CloseNotifier).CloseNotify()
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
// grab the game id from the path
params := mux.Vars(r)
id, ok := params["id"]
if !ok {
http.Error(w, "no 'id' found in URL", http.StatusBadRequest)
return
}
// convert to an int
i, err := strconv.Atoi(id)
if err != nil {
log.Println(err.Error())
http.Error(w, fmt.Sprintf("failed to convert game id [%s] to int", id), http.StatusInternalServerError)
return
}
queryParams := r.URL.Query()
playerName := queryParams.Get("name")
// verify requested game exists
_, ok = games[i]
if !ok {
log.Println("failed to verify that game exists")
http.Error(w, fmt.Sprintf("game id [%s] not found", id), http.StatusBadRequest)
return
}
log.Printf("listening to game: %d", i)
// generate player id
playerID := rand.Intn(gameCodeMax-gameCodeMin) + gameCodeMin
if _, ok := players[playerID]; ok {
log.Println(err.Error())
http.Error(w, "random player id collision. do a better job!", http.StatusInternalServerError)
return
}
players[playerID] = player{
GameID: i,
PlayerID: playerID,
Name: playerName,
}
thisClientCh := make(chan message)
games[i] = append(games[i], thisClientCh)
go func() {
<-notify
// close(thisClientCh)
// we need to close this client's channel and remove it to avoid creating a leak.
hostCh <- message{
GameID: i,
PlayerID: playerID,
Action: "disconnect",
}
log.Println("disconnect")
}()
// send initial message
resp := map[string]interface{}{
"time": time.Now().Local().String(),
"gameID": i,
"playerID": playerID,
"playerName": playerName,
}
jsonBytes, err := json.Marshal(resp)
if err != nil {
log.Println(err.Error())
http.Error(w, "failed to encode response", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "data: %s\n\n", string(jsonBytes))
flusher.Flush()
// end initial message
hostCh <- message{
GameID: i,
PlayerID: playerID,
Action: "joined",
}
for {
msg := <-thisClientCh
resp := map[string]interface{}{
"time": time.Now().Local().String(),
"gameID": msg.GameID,
"playerID": msg.PlayerID,
"playerName": players[msg.PlayerID].Name,
"action": msg.Action,
}
jsonBytes, err := json.Marshal(resp)
if err != nil {
log.Println(err.Error())
http.Error(w, "failed to encode response", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "data: %s\n\n", string(jsonBytes))
flusher.Flush()
}
log.Println("connection closed")
}
// HostListenHandler establishes a stream and sends SSE related to host features.
func HostListenHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Got connection: %s", r.Proto)
notify := w.(http.CloseNotifier).CloseNotify()
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
params := mux.Vars(r)
id, ok := params["id"]
if !ok {
http.Error(w, "no 'id' found in URL", http.StatusBadRequest)
return
}
i, err := strconv.Atoi(id)
if err != nil {
log.Println(err.Error())
http.Error(w, fmt.Sprintf("failed to convert game id [%s] to int", id), http.StatusInternalServerError)
return
}
_, ok = games[i]
if !ok {
http.Error(w, fmt.Sprintf("game id [%s] not found", id), http.StatusBadRequest)
return
}
go func() {
<-notify
// close(thisClientCh)
// we need to close this client's channel and remove it to avoid creating a leak.
serverCh <- message{
GameID: i,
Action: "disconnect",
}
}()
log.Printf("HOST listening to game to game: %d", i)
for {
msg := <-hosts[i]
resp := map[string]interface{}{
"time": time.Now().Local().String(),
"gameID": msg.GameID,
"playerID": msg.PlayerID,
"playerName": players[msg.PlayerID].Name,
"action": msg.Action,
}
jsonBytes, err := json.Marshal(resp)
if err != nil {
http.Error(w, "failed to encode response", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "data: %s\n\n", string(jsonBytes))
flusher.Flush()
}
}