-
Notifications
You must be signed in to change notification settings - Fork 68
/
caller.go
77 lines (67 loc) · 1.33 KB
/
caller.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
package socketio_client
import (
"errors"
"fmt"
"reflect"
"sync"
)
type caller struct {
sync.RWMutex
Func reflect.Value
Args []reflect.Type
}
func newCaller(f interface{}) (*caller, error) {
fv := reflect.ValueOf(f)
if fv.Kind() != reflect.Func {
return nil, fmt.Errorf("f is not func")
}
ft := fv.Type()
if ft.NumIn() == 0 {
return &caller{
Func: fv,
}, nil
}
args := make([]reflect.Type, ft.NumIn())
for i, n := 0, ft.NumIn(); i < n; i++ {
args[i] = ft.In(i)
}
return &caller{
Func: fv,
Args: args,
}, nil
}
func (c *caller) GetArgs() []interface{} {
c.RLock()
defer c.RUnlock()
ret := make([]interface{}, len(c.Args))
for i, argT := range c.Args {
if argT.Kind() == reflect.Ptr {
argT = argT.Elem()
}
v := reflect.New(argT)
ret[i] = v.Interface()
}
return ret
}
func (c *caller) Call(args []interface{}) []reflect.Value {
c.RLock()
defer c.RUnlock()
var a []reflect.Value
diff := 0
a = make([]reflect.Value, len(args))
for i, arg := range args {
v := reflect.ValueOf(arg)
if c.Args[i].Kind() != reflect.Ptr {
if v.IsValid() {
v = v.Elem()
} else {
v = reflect.Zero(c.Args[i])
}
}
a[i+diff] = v
}
if len(args) != len(c.Args) {
return []reflect.Value{reflect.ValueOf([]interface{}{}), reflect.ValueOf(errors.New("Arguments do not match"))}
}
return c.Func.Call(a)
}