-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
110 lines (97 loc) · 2.39 KB
/
main.go
File metadata and controls
110 lines (97 loc) · 2.39 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
109
110
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"os"
"time"
"github.com/Senior-Design-Kappa/sync-server/controller"
"github.com/Senior-Design-Kappa/sync-server/models"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
var (
addr = ":8000"
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
c *controller.Controller
)
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
hashLength = 64
)
func main() {
if os.Getenv("ADDR") != "" {
addr = os.Getenv("ADDR")
}
c = controller.NewController()
go c.Run()
r := mux.NewRouter()
r.HandleFunc("/health", health)
r.HandleFunc("/connect/{roomID}", handleConnection)
s := http.Server{
Handler: r,
Addr: addr,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Printf("Listening and serving on %s\n", addr)
log.Fatal(s.ListenAndServe())
}
// health reports 200 if services is up and running
func health(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "OK")
}
func generateHash(n int) string {
src := rand.NewSource(time.Now().UnixNano())
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
// handleConnection handles websocket requests from client
func handleConnection(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
vals := mux.Vars(r)
roomID, ok := vals["roomID"]
if !ok {
// handle invalid roomID
log.Printf("Invalid roomID\n")
http.Error(w, "Room not found", 404)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
hash := generateHash(hashLength)
nc := &models.NewConnection{
Conn: conn,
Room: roomID,
Hash: hash,
}
c.Register <- nc
}