-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
87 lines (74 loc) · 1.64 KB
/
http.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
package main
import (
"crypto/rand"
"encoding/base64"
"github.com/gorilla/websocket"
"html/template"
"net/http"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
var (
connections map[string]*websocket.Conn = make(map[string]*websocket.Conn)
keys map[string]string = make(map[string]string)
)
type Message struct {
Type string `json:"type"`
Id string `json:"id"`
Message string `json:"message"`
}
func startWebServer() {
http.HandleFunc("/ws", handleWebsockets)
http.HandleFunc("/", handleRoot)
http.ListenAndServe("[::]:5001", nil)
wg.Done()
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("index.html")
if err != nil {
// If there was a problem, stop
return
}
// Generate random id for users
bytes := make([]byte, 32)
_, err = rand.Read(bytes)
if err != nil {
return
}
tmpl.ExecuteTemplate(w, "index", struct {
Id string
}{
Id: base64.URLEncoding.EncodeToString(bytes),
})
}
func handleWebsockets(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
// Save the id to help with deleting the connection later
var id string
for {
var message Message
err := conn.ReadJSON(&message)
if err != nil {
// Only delete the connection and keys if we ever saved it with the id
if id != "" {
delete(connections, id)
delete(keys, id)
}
break
}
// Save connection and id if they're not already set
if id == "" {
id = message.Id
connections[id] = conn
}
switch message.Type {
case "SAVE-KEY":
keys[id] = message.Message
}
}
}