-
Notifications
You must be signed in to change notification settings - Fork 1
/
hook.go
83 lines (71 loc) · 2.04 KB
/
hook.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
// Copyright The Jet authors. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package hook
import (
"reflect"
)
type Hook struct {
PostParamsParseHooks []*reflect.Value
PostMethodExecuteHooks []*reflect.Value
PreMethodExecuteHooks []*reflect.Value
}
// GenHook see handle#AddHook
func (hook *Hook) GenHook(rcvr *reflect.Value) *Hook {
if methodByName := rcvr.MethodByName("PostParamsParseHook"); methodByName.IsValid() {
hook.PostParamsParseHooks = append(hook.PostParamsParseHooks, &methodByName)
}
if methodByName := rcvr.MethodByName("PostMethodExecuteHook"); methodByName.IsValid() {
hook.PostMethodExecuteHooks = append(hook.PostMethodExecuteHooks, &methodByName)
}
if methodByName := rcvr.MethodByName("PreMethodExecuteHook"); methodByName.IsValid() {
hook.PreMethodExecuteHooks = append(hook.PreMethodExecuteHooks, &methodByName)
}
return hook
}
func (hook *Hook) PostParamsParse(param reflect.Value) (err error) {
for _, h := range hook.PostParamsParseHooks {
// call
result := h.Call([]reflect.Value{param})
// handle error
if !result[0].IsNil() {
err = result[0].Interface().(error)
return
}
}
return
}
func (hook *Hook) HasMethodExecuteHook() bool {
return len(hook.PostMethodExecuteHooks) != 0
}
func (hook *Hook) PostMethodExecuteHook(param reflect.Value) (data any, err error) {
for _, h := range hook.PostMethodExecuteHooks {
// call
result := h.Call([]reflect.Value{param})
// handle error
if !result[1].IsNil() {
err = result[1].Interface().(error)
return
}
// handle data
if !result[0].IsNil() {
data = result[0].Interface()
}
}
return
}
func (hook *Hook) HasPreMethodExecuteHooks() bool {
return len(hook.PostMethodExecuteHooks) != 0
}
func (hook *Hook) PreMethodExecuteHook(ctx reflect.Value) (err error) {
for _, h := range hook.PreMethodExecuteHooks {
// call
result := h.Call([]reflect.Value{ctx})
// handle error
if !result[0].IsNil() {
err = result[0].Interface().(error)
return
}
}
return
}