-
Notifications
You must be signed in to change notification settings - Fork 3
/
router.go
255 lines (205 loc) · 5.37 KB
/
router.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package stdapi
import (
"context"
"fmt"
"net"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
type HandlerFunc func(c *Context) error
type Middleware func(fn HandlerFunc) HandlerFunc
type Router struct {
*mux.Router
Middleware []Middleware
Parent *Router
Server *Server
}
type Route struct {
*mux.Route
Router *Router
}
func (rt *Router) MatcherFunc(fn mux.MatcherFunc) *Router {
return &Router{
Parent: rt,
Router: rt.Router.MatcherFunc(fn).Subrouter(),
Server: rt.Server,
}
}
func (rt *Router) HandleNotFound(fn HandlerFunc) {
rt.Router.NotFoundHandler = rt.http(fn)
}
func (rt *Router) Redirect(method, path string, code int, target string) {
rt.Handle(path, Redirect(code, target)).Methods(method)
}
func (rt *Router) Route(method, path string, fn HandlerFunc) Route {
switch method {
case "SOCKET":
return Route{
Route: rt.Handle(path, rt.websocket(fn)).Methods("GET").Headers("Upgrade", "websocket"),
Router: rt,
}
case "ANY":
return Route{
Route: rt.Handle(path, rt.http(fn)),
Router: rt,
}
default:
return Route{
Route: rt.Handle(path, rt.http(fn)).Methods(method),
Router: rt,
}
}
}
func (rt *Router) Static(path string, files FileSystem) Route {
prefix := fmt.Sprintf("%s/", path)
return Route{
Route: rt.PathPrefix(prefix).Handler(http.StripPrefix(prefix, http.FileServer(files))),
Router: rt,
}
}
func (rt *Router) Subrouter(prefix string, fn func(*Router)) {
fn(&Router{
Parent: rt,
Router: rt.PathPrefix(prefix).Subrouter(),
Server: rt.Server,
})
}
func (rt *Router) Use(mw Middleware) {
rt.Middleware = append(rt.Middleware, mw)
}
func (rt *Router) UseHandlerFunc(fn http.HandlerFunc) {
rt.Middleware = append(rt.Middleware, func(gn HandlerFunc) HandlerFunc {
return func(c *Context) error {
fn(c.response, c.request)
return gn(c)
}
})
}
func (rt *Router) context(name string, w http.ResponseWriter, r *http.Request, conn *websocket.Conn) (*Context, error) {
id, err := generateId(12)
if err != nil {
return nil, errors.WithStack(err)
}
w.Header().Add("Request-Id", id)
c := NewContext(w, r)
c.context = context.WithValue(r.Context(), "request.id", id)
c.id = id
c.logger = rt.Server.Logger.Prepend("id=%s", id).At(name)
c.name = name
c.ws = conn
return c, nil
}
func (rt *Router) handle(fn HandlerFunc, c *Context) error {
defer func() {
if rt.Server.Recover == nil {
return
}
err := recover()
if err == http.ErrAbortHandler || err == nil {
return
}
switch t := err.(type) {
case error:
rt.Server.Recover(t, c)
case string:
rt.Server.Recover(fmt.Errorf(t), c)
case fmt.Stringer:
rt.Server.Recover(fmt.Errorf(t.String()), c)
default:
panic(t)
}
}()
c.logger = c.logger.Append("method=%q path=%q", c.request.Method, c.request.URL.Path).Start()
// rw := &responseWriter{ResponseWriter: c.response, code: 200}
// c.response = rw
mw := []Middleware{}
p := rt.Parent
for {
if p == nil {
break
}
mw = append(p.Middleware, mw...)
p = p.Parent
}
mw = append(mw, rt.Middleware...)
fnmw := rt.wrap(fn, mw...)
errr := fnmw(c) // non-standard error name to avoid wrapping
if ne, ok := errr.(*net.OpError); ok {
c.logger.Logf("state=closed error=%q", ne.Err)
return nil
}
code := c.response.Code()
if code == 0 {
code = 200
}
c.logger.Logf("response=%d", code)
return errr
}
func (rt *Router) http(fn HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c, err := rt.context(functionName(fn), w, r, nil)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if err := rt.handle(fn, c); err != nil {
switch t := err.(type) {
case Error:
c.logger.Append("code=%d", t.Code()).Error(err)
http.Error(c.response, t.Error(), t.Code())
case error:
c.logger.Error(err)
http.Error(c.response, t.Error(), http.StatusInternalServerError)
}
}
}
}
var upgrader = websocket.Upgrader{ReadBufferSize: 10 * 1024, WriteBufferSize: 10 * 1024}
func (rt *Router) websocket(fn HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
w.Write([]byte(fmt.Sprintf("ERROR: %s\n", err.Error())))
return
}
// empty binary message signals EOF
defer conn.WriteMessage(websocket.BinaryMessage, []byte{})
// defer conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(1000, ""))
c, err := rt.context(functionName(fn), w, r, conn)
if err != nil {
conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("ERROR: %s\n", err.Error())))
return
}
if err := rt.handle(fn, c); err != nil {
conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("ERROR: %s\n", err.Error())))
return
}
}
}
func (rt *Router) wrap(fn HandlerFunc, m ...Middleware) HandlerFunc {
if len(m) == 0 {
return fn
}
return m[0](rt.wrap(fn, m[1:len(m)]...))
}
// type responseWriter struct {
// http.ResponseWriter
// bytes int64
// code int
// }
// func (w *responseWriter) Flush() {
// if f, ok := w.ResponseWriter.(http.Flusher); ok {
// f.Flush()
// }
// }
// func (w *responseWriter) Write(data []byte) (int, error) {
// n, err := w.ResponseWriter.Write(data)
// w.bytes += int64(n)
// return n, err
// }
// func (w *responseWriter) WriteHeader(code int) {
// w.code = code
// w.ResponseWriter.WriteHeader(code)
// }