-
Notifications
You must be signed in to change notification settings - Fork 2
/
handlers.go
230 lines (189 loc) · 5.37 KB
/
handlers.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
225
226
227
228
229
230
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
// TemplateResponse contains the information needed to render the past and future templates
type TemplateResponse struct {
Talks []*Talk
HumanWeek string
Week string
NextWeek string
PrevWeek string
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
week := nextWednesday()
// Validate week and get human readable version
human, _ := weekForHumans(week)
// Prepare response
talks := talks.VisibleTalks(week)
res := TemplateResponse{Talks: talks, Week: week, HumanWeek: human, NextWeek: addWeek(week), PrevWeek: subtractWeek(week)}
// Render the template
err := tmpls.ExecuteTemplate(w, "future.html", res)
if err != nil {
log.Println("[WARN] Failed to render template:", err)
}
}
// /{week:[0-9]{8}}
func weekHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
week := vars["week"]
// Validate week and get human readable version
human, err := weekForHumans(week)
if err != nil {
log.Println("[WARN] Requested invalid week:", week)
w.WriteHeader(400)
return
}
// Prepare response
res := TemplateResponse{Week: week, HumanWeek: human, NextWeek: addWeek(week), PrevWeek: subtractWeek(week)}
// Render the template
if isPast(nextWednesday(), week) {
res.Talks = talks.AllTalks(week)
err = tmpls.ExecuteTemplate(w, "past.html", res)
} else {
res.Talks = talks.VisibleTalks(week)
err = tmpls.ExecuteTemplate(w, "future.html", res)
}
if err != nil {
log.Println("[WARN] Failed to render template:", err)
}
}
func indexTalksHandler(w http.ResponseWriter, r *http.Request) {
week := nextWednesday()
// Validate week and get human readable version
_, err := weekForHumans(week)
if err != nil {
log.Println("[WARN] Invalid week:", week)
w.WriteHeader(400)
return
}
talks := talks.AllTalks(week)
// Parse talks as JSON
err = json.NewEncoder(w).Encode(talks)
if err != nil {
log.Println("[WARN] Failed to encode talks:", err)
}
}
// /{week:[0-9]{8}}/talks returns json of talks for a given week
func talksHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
week := vars["week"]
// Validate week and get human readable version
_, err := weekForHumans(week)
if err != nil {
log.Println("[WARN] Invalid week:", week)
w.WriteHeader(400)
return
}
talks := talks.AllTalks(week)
// Parse talks as JSON
err = json.NewEncoder(w).Encode(talks)
if err != nil {
log.Println("[WARN] Failed to encode talks:", err)
}
}
// /img/{id}
func imageHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
// Lock the cache
cacheLock.RLock()
defer cacheLock.RUnlock()
// Decode the id ([32]byte)
hash, err := base64.URLEncoding.DecodeString(id)
if err != nil {
log.Println("[WARN] failed to decode image id:", err)
w.WriteHeader(400)
return
}
if len(hash) != 32 {
log.Println("[WARN]", "Invalid hash length")
w.WriteHeader(400)
return
}
// Copy the hash into a new [32]byte
var hash32 [32]byte
copy(hash32[:], hash)
// Get the image from the cache
image, ok := cache[hash32]
if !ok {
w.WriteHeader(404)
return
}
// Write the image to the response
w.Header().Set("Content-Type", image.ContentType)
w.Write(image.Data)
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
// Return list of active clients for diagnostic purposes
w.WriteHeader(200)
w.Write([]byte(fmt.Sprint(hub.countConnections())))
}
func socketHandler(w http.ResponseWriter, r *http.Request) {
// Upgrade the connection to a websocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("[WARN] failed to upgrade connection:", err)
return
}
addr, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
ip := net.ParseIP(addr)
authenticated := false
if trustedNetworks.Contains(ip) {
// Could be a load balancer, check the X-REAL-IP header
if realIP := r.Header.Get("X-Forwarded-For"); realIP != "" {
// Check if the real IP is in the trusted network
ip = net.ParseIP(realIP)
if trustedNetworks.Contains(ip) {
authenticated = true
}
} else {
authenticated = true
}
}
log.Printf("[INFO] New connection from %s (authenticated: %t)", ip, authenticated)
client := &Client{conn: conn, send: make(chan []byte), auth: authenticated}
hub.register <- client
// Run send and receive in goroutines
go client.write()
go client.read()
// Send an authentication response
client.send <- authenticatedMessage(authenticated)
}
// Post contains the information needed to render a markdown post
type Post struct {
Title string
Content string
}
// Creates a handler that serves static html after rendering markdown
func markdownFactory(post string) func(http.ResponseWriter, *http.Request) {
path := "posts/" + post + ".md"
// Read content from file
content, err := os.ReadFile(path)
if err != nil {
log.Fatal("[FATAL] Failed to read markdown file:", err)
}
// Create a dummy writer to capture the output of the template
buff := bytes.NewBuffer(nil)
// Render the markdown
err = tmpls.ExecuteTemplate(buff, "markdown.html", Post{
Title: post,
Content: string(content),
})
if err != nil {
log.Fatal("[FATAL] Failed to render markdown template:", err)
}
return func(w http.ResponseWriter, r *http.Request) {
w.Write(buff.Bytes())
}
}