-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcall.go
77 lines (64 loc) · 2.24 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
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 runtask
import (
"fmt"
"reflect"
"strconv"
)
func convertToType(value string, targetType reflect.Type) (reflect.Value, error) {
valueOf := reflect.ValueOf(value)
if valueOf.CanConvert(targetType) {
return valueOf.Convert(targetType), nil
}
var convertedValue reflect.Value
var err error
switch targetType.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var intValue int64
intValue, err = strconv.ParseInt(value, 10, targetType.Bits())
convertedValue = reflect.ValueOf(intValue).Convert(targetType)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
var uintValue uint64
uintValue, err = strconv.ParseUint(value, 10, targetType.Bits())
convertedValue = reflect.ValueOf(uintValue).Convert(targetType)
case reflect.Float32, reflect.Float64:
var floatValue float64
floatValue, err = strconv.ParseFloat(value, targetType.Bits())
convertedValue = reflect.ValueOf(floatValue).Convert(targetType)
case reflect.Bool:
var boolValue bool
boolValue, err = strconv.ParseBool(value)
convertedValue = reflect.ValueOf(boolValue)
default:
err = fmt.Errorf("unsupported string conversion to %s", targetType)
}
if err != nil {
return reflect.Value{}, fmt.Errorf("converting string to %s: %v", targetType, err)
}
return convertedValue, nil
}
func CallFunc(fn reflect.Value, args []string) ([]reflect.Value, error) {
var inArgs []reflect.Value
fnType := fn.Type()
numArgs := fnType.NumIn()
isVariadic := fnType.IsVariadic()
if isVariadic && len(args) < numArgs-1 ||
!isVariadic && len(args) != numArgs {
return nil, fmt.Errorf("wrong parameter count")
}
for i, argValue := range args {
var argType reflect.Type
// Determine the type of the current argument
if isVariadic && i >= numArgs-1 {
argType = fnType.In(numArgs - 1).Elem() // Get the element type of the variadic slice
} else {
argType = fnType.In(i)
}
// Convert the argument to the required type
convertedArg, err := convertToType(argValue, argType)
if err != nil {
return nil, fmt.Errorf("converting argument %d: %v", i, err)
}
inArgs = append(inArgs, convertedArg)
}
return fn.Call(inArgs), nil
}