This repository was archived by the owner on Mar 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaller.go
More file actions
77 lines (66 loc) · 1.72 KB
/
caller.go
File metadata and controls
77 lines (66 loc) · 1.72 KB
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 easyworker
import (
"fmt"
"log"
"reflect"
)
/*
call user's function througth reflect.
*/
func invokeFun(fun any, args ...any) (ret []any, err error) {
// catch if panic by user code.
defer func() {
if r := recover(); r != nil {
if printLog {
log.Println("user function was panic, ", r)
}
err = fmt.Errorf("user function was panic, %s", r)
}
}()
//log.Println("list args: ", args)
fn := reflect.ValueOf(fun)
fnType := fn.Type()
numIn := fnType.NumIn()
if numIn > len(args) {
return nil, fmt.Errorf("function must have minimum %d params. Have %d", numIn, len(args))
}
if numIn != len(args) && !fnType.IsVariadic() {
return nil, fmt.Errorf("func must have %d params. Have %d", numIn, len(args))
}
params := make([]reflect.Value, len(args))
for i := 0; i < len(args); i++ {
var inType reflect.Type
if fnType.IsVariadic() && i >= numIn-1 {
inType = fnType.In(numIn - 1).Elem()
} else {
inType = fnType.In(i)
}
argValue := reflect.ValueOf(args[i])
if !argValue.IsValid() {
return nil, fmt.Errorf("func Param[%d] must be %s. Have %s", i, inType, argValue.String())
}
argType := argValue.Type()
if argType.ConvertibleTo(inType) {
params[i] = argValue.Convert(inType)
} else {
return nil, fmt.Errorf("method Param[%d] must be %s. Have %s", i, inType, argType)
}
}
result := fn.Call(params)
ret = make([]any, len(result))
for i, r := range result {
ret[i] = r.Interface()
}
//log.Println("invoke result:", result)
return
}
/*
verify if interface is a function.
if interface is not a function, it will return an error.
*/
func verifyFunc(fun any) error {
if v := reflect.ValueOf(fun); v.Kind() != reflect.Func {
return fmt.Errorf("not a function")
}
return nil
}