-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
108 lines (89 loc) · 2.02 KB
/
main.go
File metadata and controls
108 lines (89 loc) · 2.02 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
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"encoding/json"
"log"
"net/http"
"unicode/utf8"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // TODO: Redo this
},
}
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan string)
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Error upgrading connection: %v", err)
return
}
defer ws.Close()
clients[ws] = true
maps, err := getAvailableMaps()
if err != nil {
log.Printf("Error getting maps: %v", err)
} else {
mapsJSON, _ := json.Marshal(map[string]interface{}{
"type": "maps_list",
"maps": maps,
"map_name": getMapName(),
})
ws.WriteMessage(websocket.TextMessage, mapsJSON)
}
for {
_, _, err := ws.ReadMessage()
if err != nil {
delete(clients, ws)
break
}
}
}
func sanitizeJSON(input string) string {
if !utf8.ValidString(input) {
validBytes := make([]byte, 0, len(input))
for i, c := range input {
if c == utf8.RuneError {
continue
}
validBytes = append(validBytes, input[i])
}
input = string(validBytes)
}
var js json.RawMessage
if err := json.Unmarshal([]byte(input), &js); err != nil {
log.Printf("Invalid JSON from C function: %v", err)
return "{}"
}
return input
}
func handleMessages() {
for {
msg := <-broadcast
msg = sanitizeJSON(msg)
for client := range clients {
err := client.WriteMessage(websocket.TextMessage, []byte(msg))
if err != nil {
log.Printf("Error: %v", err)
client.Close()
delete(clients, client)
}
}
}
}
func main() {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.HandleFunc("/ws", handleConnections)
go handleMessages()
err := InitializeReader()
if err != nil {
log.Fatal("Error initializing reader: ", err)
}
log.Println("Server starting at http://localhost:8080")
err = http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}