/
handlers.go
106 lines (85 loc) · 2.09 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
package web
import (
"fmt"
"html/template"
"log"
"net/http"
)
type indexHandler struct{ App }
func (ih *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := ih.App.GetClient(r)
// Web address to use in template
addr := fmt.Sprintf("%s%s", r.Host, ih.App.Address)
// Show welcome page by default
defaultUrl := fmt.Sprintf("http://%s/welcome?client=%s", addr, c.Id)
// Get URLs from database
urls, err := ih.App.Database.FetchUrls()
if err != nil {
log.Println(err)
return
}
// Load template, parse vars, write to client
t, err := template.New("index").Parse(indexTemplate)
if err != nil {
log.Println(err)
return
}
t.Execute(w, struct {
Address template.URL
DefaultUrl template.URL
Client string
URLs []string
}{
template.URL(addr),
template.URL(defaultUrl),
c.Id,
urls,
})
}
type welcomeHandler struct{ App }
func (wh *welcomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := wh.App.GetClient(r)
// Load template, parse vars, write to client
t, _ := template.New("welcome").Parse(welcomeTemplate)
t.Execute(w, struct {
Client string
RemoteAddr string
}{
c.Id,
c.RemoteAddr,
})
}
type consoleHandler struct{ App }
func (ah *consoleHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := ah.App.GetClient(r)
// Web address to use in template
addr := fmt.Sprintf("%s%s", r.Host, ah.App.Address)
// Load template, parse vars, write to client
t, _ := template.New("console").Parse(consoleTemplate)
t.Execute(w, struct {
Address template.URL
Client string
RemoteAddr string
}{
template.URL(addr),
c.Id,
c.RemoteAddr,
})
}
type websocketHandler struct{ App }
func (wh *websocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
}
c := wh.App.GetClient(r)
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
id := c.Id
client := NewWebsocketClient(wh.Database, ws, id, r.RemoteAddr)
hub.register <- client
go client.writePump()
client.readPump(wh.App.Database)
}