-
Notifications
You must be signed in to change notification settings - Fork 0
/
call.go
52 lines (43 loc) · 1.22 KB
/
call.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
package call
import (
"errors"
"reflect"
)
type Handle func() any
type CallMap struct {
m map[string]Handle
}
func NewCall() CallMap {
return CallMap{
m: map[string]Handle{},
}
}
func (c *CallMap) Register(register_name string, func_new Handle) {
c.m[register_name] = func_new
}
func (c *CallMap) Invok(register_name string, method_name string, params ...interface{}) ([]reflect.Value, error) {
bind_handle, ok := c.m[register_name]
if !ok {
return []reflect.Value{}, errors.New("handle is not registed")
}
bind_struct := bind_handle()
r_struct := reflect.ValueOf(bind_struct)
//必须是结构体指针
if r_struct.Kind() != reflect.Ptr || r_struct.Elem().Kind() != reflect.Struct {
return []reflect.Value{}, errors.New("handle must return struct ptr")
}
r_method, ok := r_struct.Type().MethodByName(method_name)
if !ok {
return []reflect.Value{}, errors.New("struct method is not exits")
}
if len(params)+1 != r_method.Type.NumIn() {
return []reflect.Value{}, errors.New("struct method number of params is not adapted")
}
in := make([]reflect.Value, len(params)+1)
in[0] = r_struct
for k, param := range params {
in[k+1] = reflect.ValueOf(param)
}
result := r_method.Func.Call(in)
return result, nil
}