-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
224 lines (201 loc) · 5.38 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
package main
import (
"app"
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/gorilla/pat"
"github.com/gorilla/websocket"
"github.com/urfave/negroni"
"html/template"
"log"
"net/http"
"os"
"time"
)
// Redis connection pool
var pool *redis.Pool
func newPool(addr string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", addr)
},
}
}
// HTTP Request handlers
// Home handler serves the main page
func homeHandler(wr http.ResponseWriter, req *http.Request) {
// Get userid
var userId string
userIdCookie, err := req.Cookie("loveliouid")
userId = userIdCookie.Value
// Get boards
conn := pool.Get()
defer conn.Close()
boardNames := app.GetUserBoards(conn, userId)
type Renderable struct {
UserId string
BoardNames []app.BoardName
}
var render Renderable = Renderable{
userId,
boardNames,
}
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
http.Error(wr, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(wr, render); err != nil {
http.Error(wr, err.Error(), http.StatusInternalServerError)
}
}
// This handles the case where a userid (uuid) is passed as the url
// If the uuid exists, it is set as the userid cookie and redirects to the frontpage
func userIdHandler(wr http.ResponseWriter, req *http.Request) {
userId := req.URL.Query().Get(":userid")
fmt.Sprintf("userid %v", userId)
conn := pool.Get()
defer conn.Close()
exists, _ := redis.Bool(conn.Do("EXISTS", userId))
if exists {
newCookie := &http.Cookie{
Name: "loveliouid",
Value: userId,
MaxAge: 0,
}
http.SetCookie(wr, newCookie)
}
http.Redirect(wr, req, "/", 302)
}
func healthHandler(wr http.ResponseWriter, req *http.Request) {
wr.WriteHeader(200)
wr.Write([]byte("ok"))
}
// This deletes the userid cookie and redirects to the homepage
// Mostly for testing etc
func forgetHandler(wr http.ResponseWriter, req *http.Request) {
newCookie := &http.Cookie{
Name: "loveliouid",
Value: "",
MaxAge: -1,
}
http.SetCookie(wr, newCookie)
http.Redirect(wr, req, "/", 302)
}
// Websocket stuff
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type Message struct {
MessageType string `json:"type"`
Body interface{} `json:"body"`
}
func websocketHandler(wr http.ResponseWriter, req *http.Request) {
sock, _ := upgrader.Upgrade(wr, req, nil)
userIdCookie, _ := req.Cookie("loveliouid")
userId := userIdCookie.Value
go func() {
for {
var msg Message
err := sock.ReadJSON(&msg)
if err != nil {
return
}
conn := pool.Get()
defer conn.Close()
switch msg.MessageType {
case "newBoard":
body, _ := msg.Body.(map[string]interface{})
boardName, _ := body["name"].(string)
boardInfo := app.NewBoard(conn, userId, boardName)
var reply = Message{"newBoard", boardInfo}
sock.WriteJSON(reply)
case "newBoardItem":
body, _ := msg.Body.(map[string]interface{})
itemName, _ := body["name"].(string)
boardId, _ := body["boardId"].(string)
app.NewBoardItem(conn, boardId, itemName)
boardItems := app.GetBoardItems(conn, boardId)
var reply = Message{"getBoardItems", boardItems}
sock.WriteJSON(reply)
case "getBoardItems":
body, _ := msg.Body.(map[string]interface{})
boardId, _ := body["boardId"].(string)
boardItems := app.GetBoardItems(conn, boardId)
var reply = Message{"getBoardItems", boardItems}
sock.WriteJSON(reply)
case "mutateItem":
body, _ := msg.Body.(map[string]interface{})
boardId, _ := body["boardId"].(string)
itemName, _ := body["itemName"].(string)
delta, _ := body["delta"].(string)
if delta == "incr" {
app.IncrementBoardItem(conn, boardId, itemName)
} else {
app.DecrementBoardItem(conn, boardId, itemName)
}
}
}
}()
}
// Middlewares
// UserIdCookieMiddleware guarantees that the user's request will have their ID attached as a cookie
// secure no?
func UserIdCookieMiddleware(wr http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
// Map containing exceptions that don't require stupid cookie auth
// like a healthcheck endpoint
var exceptions = map[string]bool{
"/health": true,
}
_, ok := exceptions[req.URL.Path]
if ok {
next(wr, req)
return
}
var userId string
_, err := req.Cookie("loveliouid")
if err != nil {
// New user created
conn := pool.Get()
defer conn.Close()
userId = app.NewUser(conn)
app.NewBoard(conn, userId, "new")
newCookie := &http.Cookie{
Name: "loveliouid",
Value: userId,
MaxAge: 0,
}
http.SetCookie(wr, newCookie)
req.AddCookie(newCookie)
}
next(wr, req)
}
func main() {
// Get variables
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
redisServer := os.Getenv("REDIS")
if redisServer == "" {
redisServer = "127.0.0.1:6379"
}
// Initialise Redis connection pool (globally scoped variable)
pool = newPool(redisServer)
// Define router and routings
router := pat.New()
router.Get("/health", healthHandler)
router.Get("/forget", forgetHandler)
router.Get("/{userid:[\\w-]{36}}", userIdHandler)
router.Get("/ws", websocketHandler)
router.Get("/", homeHandler)
// Add middlewares
n := negroni.Classic()
n.Use(negroni.HandlerFunc(UserIdCookieMiddleware))
n.UseHandler(router)
log.Print("Serving on 127.0.0.1:" + port)
log.Fatal(http.ListenAndServe(":"+port, n))
}