forked from gogap/aop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
104 lines (85 loc) · 2.08 KB
/
proxy.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package aop
import (
"reflect"
"github.com/gogap/errors"
)
type Proxy struct {
beanID string
funcs map[string]MethodMetadata
}
func NewProxy(beanID string) *Proxy {
return &Proxy{
beanID: beanID,
funcs: make(map[string]MethodMetadata),
}
}
func (p *Proxy) BeanID() string {
return p.beanID
}
func (p *Proxy) Method(fn interface{}) (method interface{}) {
methodName := ""
if methodMetadata, err := getFuncMetadata(fn); err != nil {
panic(err)
} else {
methodName = methodMetadata.Method.Name
}
if metadata, exist := p.funcs[methodName]; exist {
method = metadata.Method.Func.Interface()
return
}
return
}
func (p *Proxy) Invoke(method interface{}, args ...interface{}) (result *InvokeResult) {
methodName := ""
if methodMetadata, err := getFuncMetadata(method); err != nil {
result = &InvokeResult{
beanID: p.beanID,
methodName: methodName,
err: err,
}
} else {
methodName = methodMetadata.Method.Name
}
fnMetadata, exist := p.funcs[methodName]
if !exist {
result = &InvokeResult{
beanID: p.beanID,
methodName: methodName,
err: ErrInvokeFuncNotExist.New(errors.Params{"id": p.beanID, "method": methodName}),
}
return
}
fn := fnMetadata.Method.Func.Interface()
fnType := reflect.TypeOf(fn)
if fnType.Kind() != reflect.Func {
result = &InvokeResult{
beanID: p.beanID,
methodName: methodName,
err: ErrInvokeFuncTypeError.New(errors.Params{"id": p.beanID, "method": methodName}),
}
return
}
if fnType.NumIn() != len(args) {
result = &InvokeResult{
beanID: p.beanID,
methodName: methodName,
err: ErrWrongInvokeFuncArgsNum.New(errors.Params{"id": p.beanID, "method": methodName}),
}
return
}
inputs := make([]reflect.Value, len(args))
for i := range args {
inputs[i] = reflect.ValueOf(args[i])
}
fnValue := reflect.ValueOf(fn)
result = &InvokeResult{
beanID: p.beanID,
methodName: methodName,
err: nil,
values: fnValue.Call(inputs),
}
return
}
func (p *Proxy) registryFunc(metadata MethodMetadata) {
p.funcs[metadata.Method.Name] = metadata
}