-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmvc_controller.go
51 lines (40 loc) · 1.47 KB
/
mvc_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
package trinity
import (
"reflect"
)
// BindController registers a specified controller.
// Expects parameterless constructor of controller.
// Iterates through the controller methods and registers its actions using GetActionInfos.
func (mvcI *MvcInfrastructure) BindController(constructor interface{}) {
logger.Trace("")
value, controllerInterface := mvcI.reflectAndCheck(constructor)
controllerInfo := controllerInterface.GetInfo()
controller := controllerInfo.GetController()
mvcI.controllerConstructors[controller] = value
for _, actionInfo := range controllerInfo.GetActionInfos() {
httpMethod := "GET"
if actionInfo.method != "" {
httpMethod = actionInfo.method
}
mvcI.bindAction(controller, actionInfo.action, method(httpMethod), newMethodDescriptorFromValue(actionInfo.handler))
}
}
func (mvcI *MvcInfrastructure) reflectAndCheck(constructor interface{}) (reflect.Value, ControllerInterface) {
value := reflect.ValueOf(constructor)
if value.Kind() != reflect.Func {
panic("Incorrect constructor kind. Expected - Func, goted - " + value.Kind().String())
}
valueType := value.Type()
if valueType.NumIn() > 0 {
panic("Constructor must be parameterless.")
}
result := value.Call(emptyValues)
if len(result) != 1 {
panic("Constructor must return one value")
}
controllerInterface, ok := result[0].Interface().(ControllerInterface)
if !ok {
panic("Constructor return value must implement ControllerInterface")
}
return value, controllerInterface
}