-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp_input_handler.go
More file actions
95 lines (77 loc) · 1.76 KB
/
http_input_handler.go
File metadata and controls
95 lines (77 loc) · 1.76 KB
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
package main
import (
"context"
"fmt"
"log"
"net/http"
_ "embed"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
//go:embed index.html
var frontend []byte
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type HttpInputHandler struct {
playerService PlayerService
server *http.Server
mux *http.ServeMux
playerIdMap map[uuid.UUID]int
}
func NewHttpInputHandler(ps PlayerService) *HttpInputHandler {
handler := &HttpInputHandler{
playerService: ps,
playerIdMap: map[uuid.UUID]int{},
mux: http.NewServeMux(),
}
handler.mux.HandleFunc("GET /", handler.serveFrontend)
handler.mux.HandleFunc("GET /ws", handler.serveWebsocket)
return handler
}
func (k *HttpInputHandler) Listen(addr string) {
k.server = &http.Server{
Addr: addr,
Handler: k.mux,
}
k.server.ListenAndServe()
}
func (h *HttpInputHandler) serveFrontend(w http.ResponseWriter, req *http.Request) {
w.Write(frontend)
}
func (h *HttpInputHandler) serveWebsocket(w http.ResponseWriter, req *http.Request) {
conn, err := upgrader.Upgrade(w, req, nil)
if err != nil {
log.Println("Error upgrading connection:", err)
return
}
defer conn.Close()
uID := uuid.New()
pID := h.playerService.Join(uID)
err = conn.WriteMessage(websocket.TextMessage, fmt.Appendf([]byte{}, "c:%d", pID))
if err != nil {
log.Println("Error sending message:", err)
return
}
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println("Error reading message:", err)
break
}
switch string(msg) {
case "l":
h.playerService.TurnLeft(uID)
case "r":
h.playerService.TurnRight(uID)
}
}
}
func (k *HttpInputHandler) Close() {
if k.server == nil {
return
}
k.server.Shutdown(context.Background())
}