forked from shibukawa/tobubus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
proxy.go
64 lines (58 loc) · 1.38 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
package tobubus
import (
"errors"
"fmt"
"reflect"
"strings"
)
type Proxy struct {
instance interface{}
methods map[string]reflect.Value
privateMethods map[string]bool
}
func hasUpperPrefix(name string) bool {
prefix := name[:1]
return prefix == strings.ToUpper(prefix)
}
func NewProxy(instance interface{}) (*Proxy, error) {
if instance == nil {
return nil, errors.New("can't register nil")
}
proxy := &Proxy{
instance: instance,
methods: make(map[string]reflect.Value),
privateMethods: make(map[string]bool),
}
v := reflect.ValueOf(instance)
t := v.Type()
n := t.NumMethod()
for i := 0; i < n; i++ {
name := t.Method(i).Name
if hasUpperPrefix(name) {
proxy.methods[name] = v.MethodByName(name)
} else {
proxy.privateMethods[name] = true
}
}
return proxy, nil
}
func (p *Proxy) Call(name string, args ...interface{}) ([]interface{}, error) {
method, ok := p.methods[name]
if !ok {
if p.privateMethods[name] {
return nil, fmt.Errorf("Method '%s' is private", name)
} else {
return nil, fmt.Errorf("Method '%s' is undefined", name)
}
}
newArgs := make([]reflect.Value, len(args))
for i, arg := range args {
newArgs[i] = reflect.ValueOf(arg)
}
results := method.Call(newArgs)
newResults := make([]interface{}, len(results))
for i, result := range results {
newResults[i] = result.Interface()
}
return newResults, nil
}