-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
419 lines (359 loc) · 10.6 KB
/
server.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package rapid
import (
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"regexp"
"strconv"
"time"
"github.com/codegangsta/inject"
structschema "github.com/gorilla/schema"
)
var schemadecoder *structschema.Decoder
func init() {
schemadecoder = structschema.NewDecoder()
schemadecoder.RegisterConverter(time.Duration(0), convertDuration)
schemadecoder.RegisterConverter(time.Time{}, convertTime)
}
func convertDuration(value string) reflect.Value {
if d, err := time.ParseDuration(value); err == nil {
return reflect.ValueOf(d)
}
return reflect.Value{}
}
func convertTime(value string) reflect.Value {
if t, err := time.Parse(time.RFC3339, value); err == nil {
return reflect.ValueOf(t)
}
return reflect.Value{}
}
type Validator interface {
Validate() error
}
type Logger interface {
Debugf(fmt string, args ...interface{})
Infof(fmt string, args ...interface{})
Warningf(fmt string, args ...interface{})
Errorf(fmt string, args ...interface{})
}
type loggerSink struct{}
func (l *loggerSink) Debugf(fmt string, args ...interface{}) {}
func (l *loggerSink) Infof(fmt string, args ...interface{}) {}
func (l *loggerSink) Warningf(fmt string, args ...interface{}) {}
func (l *loggerSink) Errorf(fmt string, args ...interface{}) {}
type CloseNotifierChannel <-chan bool
// An error-conformant type that can return a HTTP status code, a message, and
// optional headers.
type HTTPStatus struct {
Status int `json:"status"`
Message string `json:"error"`
Headers http.Header `json:"-"`
}
func (h *HTTPStatus) Error() string {
return h.Message
}
func ErrorForStatus(status int) error {
return Error(status, http.StatusText(status))
}
func Error(status int, message string) error {
return ErrorWithHeaders(status, message, http.Header{})
}
func ErrorForStatusWithHeaders(status int, headers http.Header) error {
return &HTTPStatus{status, http.StatusText(status), headers}
}
func ErrorWithHeaders(status int, message string, headers http.Header) error {
return &HTTPStatus{status, message, headers}
}
type Params map[string]string
func (p Params) Int(key string) (int64, error) {
v, ok := p[key]
if !ok {
return 0, fmt.Errorf("no such query parameter %s", key)
}
return strconv.ParseInt(v, 10, 64)
}
func (p Params) Float(key string) (float64, error) {
v, ok := p[key]
if !ok {
return 0, fmt.Errorf("no such query parameter %s", key)
}
return strconv.ParseFloat(v, 64)
}
type routeMatch struct {
route *RouteSchema
pattern *regexp.Regexp
params []string
method reflect.Value
}
// A function with the signature f(...) error. Arguments can be injected.
type BeforeHandlerFunc interface{}
// A function with the signature f(...) error. Arguments can be injected.
type AfterHandlerFunc interface{}
type Server struct {
schema *Schema
matches []*routeMatch
codec CodecFactory
log Logger
Injector inject.Injector
handler interface{}
beforeHandler BeforeHandlerFunc
afterHandler AfterHandlerFunc
}
func NewServer(schema *Schema, handler interface{}) (*Server, error) {
matches := []*routeMatch{}
hr := reflect.ValueOf(handler)
for _, resource := range schema.Resources {
for _, route := range resource.Routes {
pattern, params := route.CompilePath()
method := hr.MethodByName(route.Name)
if !method.IsValid() {
return nil, fmt.Errorf("no such method %s.%s", hr.Type(), route.Name)
}
matches = append(matches, &routeMatch{
route: route,
pattern: pattern,
params: params,
method: method,
})
}
}
s := &Server{
schema: schema,
matches: matches,
codec: DefaultCodecFactory,
log: &loggerSink{},
Injector: inject.New(),
handler: handler,
}
return s, nil
}
// Specify the default CodecFactory for the server.
func (s *Server) Codec(codec CodecFactory) *Server {
s.codec = codec
return s
}
func (s *Server) Logger(log Logger) *Server {
s.log = log
return s
}
func (s *Server) BeforeHandler(before BeforeHandlerFunc) *Server {
s.beforeHandler = before
return s
}
// Register an injectable function to be called after the handler method is
// called but before the response is encoded. If the handler method writes
// its own response, this callback will not be called.
func (s *Server) AfterHandler(after AfterHandlerFunc) *Server {
s.afterHandler = after
return s
}
// Close underlying handler if it supports io.Closer.
func (s *Server) Close() error {
if closer, ok := s.handler.(io.Closer); ok {
return closer.Close()
}
return nil
}
func indirect(t reflect.Type) reflect.Type {
if t.Kind() == reflect.Ptr {
return indirect(t.Elem())
}
return t
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.log.Debugf("%s %s", r.Method, r.URL)
// Match URL and method.
match, parts := s.match(r)
if match == nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, http.StatusNotFound, nil))
return
}
i := inject.New()
i.SetParent(s.Injector)
// Decode path parameters, if any.
if match.route.PathType != nil {
path := reflect.New(indirect(match.route.PathType)).Interface()
values := url.Values{}
for key, value := range parts {
values.Add(key, value)
}
err := schemadecoder.Decode(path, values)
if err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, http.StatusBadRequest, err))
return
}
if v, ok := path.(Validator); ok {
if err := v.Validate(); err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, http.StatusBadRequest, err))
return
}
}
i.Map(path)
}
// Decode query parameters, if any.
if match.route.QueryType != nil {
query := reflect.New(indirect(match.route.QueryType)).Interface()
err := schemadecoder.Decode(query, r.URL.Query())
if err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, http.StatusBadRequest, err))
return
}
if v, ok := query.(Validator); ok {
if err := v.Validate(); err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, http.StatusBadRequest, err))
return
}
}
i.Map(query)
}
// Decode request body, if any.
if match.route.RequestType != nil {
req, reqi := makeValueAndInterface(match.route.RequestType)
err := s.codec.Request(reqi).DecodeRequest(r)
if err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, http.StatusBadRequest, err))
return
}
if v, ok := reqi.(Validator); ok {
if err := v.Validate(); err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, http.StatusBadRequest, err))
return
}
}
i.Map(req())
}
i.MapTo(i, (*inject.Injector)(nil))
i.MapTo(w, (*http.ResponseWriter)(nil))
i.Map(r)
i.Map(parts)
i.Map(match.route)
var closeNotifier CloseNotifierChannel
if cn, ok := w.(http.CloseNotifier); ok {
// WriteError(w, http.StatusInternalServerError, errors.New("HTTP writer does not support close notifications"))
// return
closeNotifier = CloseNotifierChannel(cn.CloseNotify())
i.Map(closeNotifier)
}
if s.beforeHandler != nil {
results, err := i.Invoke(s.beforeHandler)
if err != nil {
panic(err.Error())
}
rerr := results[0]
if !rerr.IsNil() {
err = rerr.Interface().(error)
if err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, 500, err))
return
}
}
}
result, err := i.Invoke(match.method.Interface())
if err != nil {
panic(err.Error())
}
switch len(result) {
case 0: // Zero return values, we assume the handler has processed the request itself.
return
case 1: // Single value is always an error, so we just synthesize (nil, error).
result = []reflect.Value{reflect.ValueOf((*struct{})(nil)), result[0]}
case 2: // (response, error)
// TODO: More checks for stuff.
default:
panic(fmt.Errorf("handler method %s.%s should return (<response>, <error>)", match.method.Type(), match.route.Name))
}
if s.afterHandler != nil {
results, err := i.Invoke(s.afterHandler)
if err != nil {
panic(err.Error())
}
rerr := results[0]
if !rerr.IsNil() {
err = rerr.Interface().(error)
if err != nil {
s.maybeLogError(s.codec.Response(nil).EncodeResponse(r, w, 500, err))
return
}
}
}
s.log.Debugf("%s %s -> %v", r.Method, r.URL, result[1].Interface())
s.handleScalar(match.route, closeNotifier, w, r, result[0], result[1])
}
func (s *Server) handleScalar(route *RouteSchema, closeNotifier CloseNotifierChannel, w http.ResponseWriter, r *http.Request, rdata reflect.Value, rerr reflect.Value) {
var data interface{}
var err error
switch rdata.Kind() {
case reflect.String:
data = rdata.String()
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
data = rdata.Int()
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
data = rdata.Uint()
case reflect.Float32, reflect.Float64:
data = rdata.Float()
default:
if !rdata.IsNil() {
data = rdata.Interface()
}
}
// If we have an error...
if !rerr.IsNil() {
err = rerr.Interface().(error)
}
_, datai := valueAndInterface(data)
s.maybeLogError(s.codec.Response(datai).EncodeResponse(r, w, 0, err))
}
func (s *Server) maybeLogError(err error) {
if err != nil {
s.log.Errorf("%s", err)
}
}
func (s *Server) match(r *http.Request) (*routeMatch, Params) {
for _, match := range s.matches {
if r.Method == match.route.Method {
matches := match.pattern.FindStringSubmatch(r.URL.Path)
if matches != nil {
params := Params{}
for i, k := range match.params {
params[k] = matches[i+1]
}
return match, params
}
}
}
return nil, nil
}
// These two functions are required to handle interface methods on value
// types. eg. RawData. Annoying. Basically, if we have a value but the
// interface methods have pointer receivers, we need to use a pointer to the
// value to check interface implementation. But to complicate life, you can't
// take the address of a reflected value. Brilliant.
func valueAndInterface(n interface{}) (func() interface{}, interface{}) {
if n == nil {
return nil, nil
}
t := reflect.TypeOf(n)
switch t.Kind() {
case reflect.Ptr:
v := reflect.ValueOf(n).Interface()
return func() interface{} { return v }, v
default:
vpv := reflect.New(t)
vpv.Elem().Set(reflect.ValueOf(n))
return func() interface{} { return reflect.Indirect(vpv).Interface() }, vpv.Interface()
}
}
func makeValueAndInterface(t reflect.Type) (func() interface{}, interface{}) {
switch t.Kind() {
case reflect.Slice:
return valueAndInterface(reflect.MakeSlice(t, 0, 0).Interface())
case reflect.Map:
return valueAndInterface(reflect.MakeMap(t).Interface())
case reflect.Ptr:
return valueAndInterface(reflect.New(t.Elem()).Interface())
default:
return valueAndInterface(reflect.New(t).Elem().Interface())
}
}