-
Notifications
You must be signed in to change notification settings - Fork 14
/
route.go
71 lines (58 loc) · 1.62 KB
/
route.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
package pairec
import (
"bytes"
"net/http"
"net/http/httptest"
"reflect"
)
type handleFunc func(http.ResponseWriter, *http.Request)
type MiddlewareFunc func(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request)
type RouteInfo struct {
pattern string
hf handleFunc
initialize func() ControllerInterface
controllerType reflect.Type
}
func Route(pattern string, c ControllerInterface) {
reflectVal := reflect.ValueOf(c)
t := reflect.Indirect(reflectVal).Type()
info := RouteInfo{
pattern: pattern,
controllerType: t,
}
info.initialize = func() ControllerInterface {
vc := reflect.New(info.controllerType)
execController, ok := vc.Interface().(ControllerInterface)
if !ok {
panic("controller is not ControllerInterface")
}
elemVal := reflect.ValueOf(c).Elem()
elemType := reflect.TypeOf(c).Elem()
execElem := reflect.ValueOf(execController).Elem()
numOfFields := elemVal.NumField()
for i := 0; i < numOfFields; i++ {
fieldType := elemType.Field(i)
elemField := execElem.FieldByName(fieldType.Name)
if elemField.CanSet() {
fieldVal := elemVal.Field(i)
elemField.Set(fieldVal)
}
}
return execController
}
PairecApp.Handlers.Register(&info)
}
func HandleFunc(pattern string, hf handleFunc) {
info := RouteInfo{
pattern: pattern,
hf: hf,
}
PairecApp.Handlers.Register(&info)
}
func Forward(method, url, body string) *http.Response {
readBuf := bytes.NewBufferString(body)
req := httptest.NewRequest(method, url, readBuf)
w := httptest.NewRecorder()
PairecApp.Handlers.ServeHTTP(w, req)
return w.Result()
}