-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
executable file
·72 lines (59 loc) · 1.67 KB
/
controller.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
package goweb
import (
"reflect"
"github.com/pkg/errors"
)
type JSONResponse struct {
StatusCode int
BodyData interface{}
}
func (r *JSONResponse) Response(resp *Response) {
resp.Header().Set("Content-Type", "application/json; charset=utf-8")
resp.WriteHeader(r.StatusCode)
resp.WriteJSON(r.BodyData)
}
type Controller struct {
MethodFuncMap map[string]*reflect.Value
}
// Invoke invoke controller method
func (cm *Controller) Invoke(req *Request, resp *Response, context *RequestContext) error {
methodRef, found := cm.MethodFuncMap[req.Req.Method]
if !found {
resp.WriteHeader(405)
return nil
}
inValues := make([]reflect.Value, 0)
inValues = append(inValues, reflect.ValueOf(req))
inValues = append(inValues, reflect.ValueOf(resp))
inValues = append(inValues, reflect.ValueOf(context))
outValues := (*methodRef).Call(inValues)
if outValues == nil || len(outValues) < 1 {
return nil
}
if !outValues[0].IsValid() {
return nil
}
first := outValues[0].Interface()
if j, ok := first.(*JSONResponse); ok {
j.Response(resp)
return nil
}
// TODO: check return type
return nil
}
// WrapController wrap controller obect, return RequestHandlerFunc
func WrapController(ins interface{}, methodMap map[string]string) (RequestHandlerFunc, error) {
v := reflect.ValueOf(ins)
methodFuncMap := make(map[string]*reflect.Value, 0)
for httpMethod, methodName := range methodMap {
controllerMethod := v.MethodByName(methodName)
if !controllerMethod.IsValid() {
return nil, errors.WithMessage(ErrMethodNotFound, methodName)
}
methodFuncMap[httpMethod] = &controllerMethod
}
mapper := &Controller{
MethodFuncMap: methodFuncMap,
}
return mapper.Invoke, nil
}