/
handlers.go
123 lines (111 loc) · 2.49 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
package main
import (
"fmt"
"github.com/gorilla/websocket"
"io/ioutil"
"log"
"net/http"
"net/url"
"unicode/utf8"
)
type wsHandler struct {
hub *hub
upgrader *websocket.Upgrader
}
func newWsHandler(hub *hub, origin string) wsHandler {
return wsHandler{
hub: hub,
upgrader: &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: wsOriginChecker(origin),
},
}
}
func wsOriginChecker(origin string) func(r *http.Request) bool {
if origin == "" {
return func(r *http.Request) bool {
return true
}
}
serverOriginURL, err := url.Parse(origin)
if err != nil {
log.Fatal("Failed to parse origin", origin, err)
}
return func(r *http.Request) bool {
o := r.Header["Origin"]
if len(o) == 0 {
return true
}
clientOrigin := o[0]
if clientOrigin == origin {
return true
}
clientOriginURL, err := url.Parse(clientOrigin)
if err != nil {
return false
}
if clientOriginURL.Scheme != serverOriginURL.Scheme {
return false
}
if clientOriginURL.Host != serverOriginURL.Host {
return false
}
return true
}
}
func (wsh wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !validateRequest(w, r) {
return
}
ws, err := wsh.upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
c := newConnection(ws, wsh.hub, r.URL.Path)
c.run()
}
type getHandler struct {
hub *hub
}
func (gh getHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !validateRequest(w, r) {
return
}
webTemplate.Execute(w, templateArgs{r.URL.Path})
}
type postHandler struct {
hub *hub
}
func (ph postHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !validateRequest(w, r) {
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
sendBadRequestError(w, "Unable to read POST body.")
return
}
ph.hub.queue <- command{cmd: PUBLISH, path: r.URL.Path, text: body}
w.Write([]byte("OK\n"))
mark("postmsgs", 1)
}
func validateRequest(w http.ResponseWriter, r *http.Request) bool {
if !utf8.ValidString(r.URL.Path) {
sendBadRequestError(w, "Path must be valid Unicode (UTF-8).")
return false
}
pathLen := utf8.RuneCountInString(r.URL.Path)
if !(pathLenMin <= pathLen && pathLen <= pathLenMax) {
sendBadRequestError(w, fmt.Sprintf(
"Path length must be %d-%d Unicode characters (UTF-8).",
pathLenMin, pathLenMax))
return false
}
return true
}
func sendBadRequestError(w http.ResponseWriter, str string) {
http.Error(w,
fmt.Sprintf("Error: bad request. %s", str),
http.StatusBadRequest)
}