Skip to content

Commit 7ef17a4

Browse files
committed
Before, after, panic, finally controller auto rule implementation
1 parent bcb9acd commit 7ef17a4

File tree

4 files changed

+223
-71
lines changed

4 files changed

+223
-71
lines changed

before_after_filter.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package revel
2+
3+
import (
4+
"reflect"
5+
)
6+
7+
// Autocalls any defined before and after methods on the target controller
8+
// If either calls returns a value then the result is returned
9+
func BeforeAfterFilter(c *Controller, fc []Filter) {
10+
defer func() {
11+
if resultValue := beforeAfterFilterInvoke(FINALLY, c); resultValue != nil && !resultValue.IsNil() {
12+
c.Result = resultValue.Interface().(Result)
13+
}
14+
}()
15+
defer func() {
16+
if err := recover(); err != nil {
17+
if resultValue := beforeAfterFilterInvoke(PANIC, c); resultValue != nil && !resultValue.IsNil() {
18+
c.Result = resultValue.Interface().(Result)
19+
}
20+
panic(err)
21+
}
22+
}()
23+
if resultValue := beforeAfterFilterInvoke(BEFORE, c); resultValue != nil && !resultValue.IsNil() {
24+
c.Result = resultValue.Interface().(Result)
25+
}
26+
fc[0](c, fc[1:])
27+
if resultValue := beforeAfterFilterInvoke(AFTER, c); resultValue != nil && !resultValue.IsNil() {
28+
c.Result = resultValue.Interface().(Result)
29+
}
30+
}
31+
32+
func beforeAfterFilterInvoke(method When, c *Controller) (r *reflect.Value) {
33+
34+
if c.Type == nil {
35+
return
36+
}
37+
var index []*ControllerFieldPath
38+
switch method {
39+
case BEFORE:
40+
index = c.Type.ControllerEvents.Before
41+
case AFTER:
42+
index = c.Type.ControllerEvents.After
43+
case FINALLY:
44+
index = c.Type.ControllerEvents.Finally
45+
case PANIC:
46+
index = c.Type.ControllerEvents.Panic
47+
}
48+
49+
if len(index) == 0 {
50+
return
51+
}
52+
for _, function := range index {
53+
result := function.Invoke(reflect.ValueOf(c.AppController), nil)[0]
54+
if !result.IsNil() {
55+
return &result
56+
}
57+
}
58+
59+
return
60+
}

controller.go

Lines changed: 0 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ type Controller struct {
4242
Validation *Validation // Data validation helpers
4343
Log logger.MultiLogger // Context Logger
4444
}
45-
4645
// The map of controllers, controllers are mapped by using the namespace|controller_name as the key
4746
var controllers = make(map[string]*ControllerType)
4847
var controllerLog = RevelLog.New("section", "controller")
@@ -488,75 +487,8 @@ func findControllers(appControllerType reflect.Type) (indexes [][]int) {
488487
return
489488
}
490489

491-
// Controller registry and types.
492-
493-
type ControllerType struct {
494-
Namespace string // The namespace of the controller
495-
ModuleSource *Module // The module for the controller
496-
Type reflect.Type
497-
Methods []*MethodType
498-
ControllerIndexes [][]int // FieldByIndex to all embedded *Controllers
499-
}
500-
501-
type MethodType struct {
502-
Name string
503-
Args []*MethodArg
504-
RenderArgNames map[int][]string
505-
lowerName string
506-
}
507-
508-
type MethodArg struct {
509-
Name string
510-
Type reflect.Type
511-
}
512-
513-
// Adds the controller to the controllers map using its namespace, also adds it to the module list of controllers.
514-
// If the controller is in the main application it is added without its namespace as well.
515-
func AddControllerType(moduleSource *Module, controllerType reflect.Type, methods []*MethodType) (newControllerType *ControllerType) {
516-
if moduleSource == nil {
517-
moduleSource = appModule
518-
}
519490

520-
newControllerType = &ControllerType{ModuleSource: moduleSource, Type: controllerType, Methods: methods, ControllerIndexes: findControllers(controllerType)}
521-
newControllerType.Namespace = moduleSource.Namespace()
522-
controllerName := newControllerType.Name()
523-
524-
// Store the first controller only in the controllers map with the unmapped namespace.
525-
if _, found := controllers[controllerName]; !found {
526-
controllers[controllerName] = newControllerType
527-
newControllerType.ModuleSource.AddController(newControllerType)
528-
if newControllerType.ModuleSource == appModule {
529-
// Add the controller mapping into the global namespace
530-
controllers[newControllerType.ShortName()] = newControllerType
531-
}
532-
} else {
533-
controllerLog.Error("AddControllerType: Attempt to register duplicate controller as ", "controller", controllerName)
534-
}
535-
controllerLog.Info("AddControllerType: Registered controller", "controller", controllerName)
536491

537-
return
538-
}
539-
540-
// Method searches for a given exported method (case insensitive)
541-
func (ct *ControllerType) Method(name string) *MethodType {
542-
lowerName := strings.ToLower(name)
543-
for _, method := range ct.Methods {
544-
if method.lowerName == lowerName {
545-
return method
546-
}
547-
}
548-
return nil
549-
}
550-
551-
// The controller name with the namespace
552-
func (ct *ControllerType) Name() string {
553-
return ct.Namespace + ct.ShortName()
554-
}
555-
556-
// The controller name without the namespace
557-
func (ct *ControllerType) ShortName() string {
558-
return strings.ToLower(ct.Type.Name())
559-
}
560492

561493
// RegisterController registers a Controller and its Methods with Revel.
562494
func RegisterController(c interface{}, methods []*MethodType) {

controller_type.go

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
package revel
2+
3+
import (
4+
"reflect"
5+
"strings"
6+
)
7+
8+
// Controller registry and types.
9+
type ControllerType struct {
10+
Namespace string // The namespace of the controller
11+
ModuleSource *Module // The module for the controller
12+
Type reflect.Type
13+
Methods []*MethodType
14+
ControllerIndexes [][]int // FieldByIndex to all embedded *Controllers
15+
ControllerEvents *ControllerTypeEvents
16+
}
17+
type ControllerTypeEvents struct {
18+
Before, After, Finally, Panic []*ControllerFieldPath
19+
}
20+
// The controller field path provides the caller the ability to invoke the call
21+
// directly
22+
type ControllerFieldPath struct {
23+
IsPointer bool
24+
FieldIndexPath[]int
25+
FunctionCall reflect.Value
26+
}
27+
28+
type MethodType struct {
29+
Name string
30+
Args []*MethodArg
31+
RenderArgNames map[int][]string
32+
lowerName string
33+
Index int
34+
}
35+
36+
type MethodArg struct {
37+
Name string
38+
Type reflect.Type
39+
}
40+
41+
// Adds the controller to the controllers map using its namespace, also adds it to the module list of controllers.
42+
// If the controller is in the main application it is added without its namespace as well.
43+
func AddControllerType(moduleSource *Module,controllerType reflect.Type,methods []*MethodType) (newControllerType *ControllerType) {
44+
if moduleSource==nil {
45+
moduleSource = appModule
46+
}
47+
48+
newControllerType = &ControllerType{ModuleSource:moduleSource,Type:controllerType,Methods:methods,ControllerIndexes:findControllers(controllerType)}
49+
newControllerType.ControllerEvents = NewControllerTypeEvents(newControllerType)
50+
newControllerType.Namespace = moduleSource.Namespace()
51+
controllerName := newControllerType.Name()
52+
53+
// Store the first controller only in the controllers map with the unmapped namespace.
54+
if _, found := controllers[controllerName]; !found {
55+
controllers[controllerName] = newControllerType
56+
newControllerType.ModuleSource.AddController(newControllerType)
57+
if newControllerType.ModuleSource == appModule {
58+
// Add the controller mapping into the global namespace
59+
controllers[newControllerType.ShortName()] = newControllerType
60+
}
61+
} else {
62+
controllerLog.Errorf("Error, attempt to register duplicate controller as %s",controllerName)
63+
}
64+
controllerLog.Debugf("Registered controller: %s", controllerName)
65+
66+
return
67+
}
68+
// Method searches for a given exported method (case insensitive)
69+
func (ct *ControllerType) Method(name string) *MethodType {
70+
lowerName := strings.ToLower(name)
71+
for _, method := range ct.Methods {
72+
if method.lowerName == lowerName {
73+
return method
74+
}
75+
}
76+
return nil
77+
}
78+
79+
// The controller name with the namespace
80+
func (ct *ControllerType) Name() (string) {
81+
return ct.Namespace + ct.ShortName()
82+
}
83+
84+
// The controller name without the namespace
85+
func (ct *ControllerType) ShortName() (string) {
86+
return strings.ToLower(ct.Type.Name())
87+
}
88+
89+
func NewControllerTypeEvents(c *ControllerType) (ce *ControllerTypeEvents) {
90+
ce = &ControllerTypeEvents{}
91+
// Parse the methods for the controller type, assign any control methods
92+
checkType := c.Type
93+
ce.check(checkType, []int{})
94+
return
95+
}
96+
97+
// Add in before after panic and finally, recursive call
98+
// Befores are ordered in revers, everything else is in order of first encountered
99+
func (cte *ControllerTypeEvents) check(theType reflect.Type, fieldPath []int) {
100+
typeChecker := func(checkType reflect.Type) {
101+
for index := 0; index < checkType.NumMethod(); index++ {
102+
m := checkType.Method(index)
103+
// Must be two arguments, the second returns the controller type
104+
// Go cannot differentiate between promoted methods and
105+
// embedded methods, this allows the embedded method to be run
106+
// https://github.com/golang/go/issues/21162
107+
if m.Type.NumOut() == 2 && m.Type.Out(1) == checkType {
108+
if checkType.Kind() == reflect.Ptr {
109+
controllerLog.Debug("Found controller type event method pointer","name", checkType.Elem().Name(),"methodname", m.Name)
110+
} else {
111+
controllerLog.Debug("Found controller type event method","name", checkType.Elem().Name(),"methodname", m.Name)
112+
}
113+
controllerFieldPath := newFieldPath(checkType.Kind() == reflect.Ptr, m.Func, fieldPath)
114+
switch strings.ToLower(m.Name) {
115+
case "before":
116+
cte.Before = append([]*ControllerFieldPath{controllerFieldPath}, cte.Before...)
117+
case "after":
118+
cte.After = append(cte.After, controllerFieldPath)
119+
case "panic":
120+
cte.Panic = append(cte.Panic, controllerFieldPath)
121+
case "finally":
122+
cte.Finally = append(cte.Finally, controllerFieldPath)
123+
}
124+
}
125+
}
126+
}
127+
128+
// Check methods of both types
129+
typeChecker(theType)
130+
typeChecker(reflect.PtrTo(theType))
131+
132+
// Check for any sub controllers, ignore any pointers to controllers revel.Controller
133+
for i := 0; i < theType.NumField(); i++ {
134+
v := theType.Field(i)
135+
136+
switch v.Type.Kind() {
137+
case reflect.Struct:
138+
cte.check(v.Type,append(fieldPath, i))
139+
}
140+
}
141+
}
142+
func newFieldPath(isPointer bool, value reflect.Value, fieldPath []int) *ControllerFieldPath{
143+
return &ControllerFieldPath{IsPointer:isPointer,FunctionCall:value,FieldIndexPath:fieldPath}
144+
}
145+
146+
func (fieldPath *ControllerFieldPath) Invoke(value reflect.Value, input []reflect.Value) (result []reflect.Value) {
147+
for _,index := range fieldPath.FieldIndexPath {
148+
// You can only fetch fields from non pointers
149+
if value.Type().Kind() == reflect.Ptr {
150+
value = value.Elem().Field(index)
151+
} else {
152+
value = value.Field(index)
153+
}
154+
}
155+
if fieldPath.IsPointer && value.Type().Kind() != reflect.Ptr {
156+
value = value.Addr()
157+
} else if !fieldPath.IsPointer && value.Type().Kind() == reflect.Ptr {
158+
value = value.Elem()
159+
}
160+
161+
return fieldPath.FunctionCall.Call(append([]reflect.Value{value}, input...))
162+
}

fakeapp_test.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
package revel
66

77
import (
8-
"io/ioutil"
9-
"log"
108
"os"
119
"path/filepath"
1210
"reflect"
@@ -84,7 +82,7 @@ func registerControllers() {
8482
Args: []*MethodArg{
8583
{"id", reflect.TypeOf((*int)(nil))},
8684
},
87-
RenderArgNames: map[int][]string{43: {"title", "hotel"}},
85+
RenderArgNames: map[int][]string{41: {"title", "hotel"}},
8886
},
8987
{
9088
Name: "Book",

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy