-
Notifications
You must be signed in to change notification settings - Fork 2
/
reflect.go
89 lines (81 loc) · 2.13 KB
/
reflect.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
78
79
80
81
82
83
84
85
86
87
88
89
package gocache
import (
"encoding/json"
"errors"
"reflect"
)
func RegsiterFunction(f interface{}, params *CacheParams) error {
t := reflect.TypeOf(f)
if t.Kind() != reflect.Func {
return errors.New("RegsiterFunction input is not a function")
}
gc, err := New(params)
if err != nil {
return err
}
if manager.cacheFuncMap == nil {
manager.cacheFuncMap = make(map[interface{}]*GoCache)
}
manager.cacheFuncMap[reflect.ValueOf(f)] = gc
return nil
}
func UnRegsiterFunction(f interface{}) error {
t := reflect.TypeOf(f)
if t.Kind() != reflect.Func {
return errors.New("RegsiterFunction input is not a function")
}
v := reflect.ValueOf(f)
if gc, ok := manager.cacheFuncMap[v]; ok {
name := gc.params.Name
gc.Clear()
delete(manager.cacheMap, name)
delete(manager.paramsMap, name)
delete(manager.cacheFuncMap, v)
return nil
}
return errors.New("no such function regsitered")
}
func Invoke(f interface{}, inputs ...interface{}) (outputs []interface{}, err error) {
t := reflect.TypeOf(f)
if t.Kind() != reflect.Func {
return nil, errors.New("RegsiterFunction input is not a function")
}
v := reflect.ValueOf(f)
if gc, ok := manager.cacheFuncMap[v]; ok {
inputsArgs := make([]interface{}, len(inputs))
for idx, input := range inputs {
inputsArgs[idx] = input
}
jsonInputBytes, e := json.Marshal(inputsArgs)
if e != nil {
return nil, e
}
jsonInputs := string(jsonInputBytes)
if gc.IsExist(jsonInputs) {
value, e := gc.Get(jsonInputs)
if !e {
return nil, errors.New("cache get failed")
} else {
return value.([]interface{}), nil
}
} else {
inputsData := make([]reflect.Value, len(inputs))
for idx, input := range inputs {
inputsData[idx] = reflect.ValueOf(input)
}
outputs = make([]interface{}, t.NumOut())
var outs []reflect.Value
if t.IsVariadic() {
outs = reflect.ValueOf(f).CallSlice(inputsData)
} else {
outs = reflect.ValueOf(f).Call(inputsData)
}
for idx, o := range outs {
outputs[idx] = o.Interface()
}
gc.Add(jsonInputs, outputs)
return outputs, nil
}
}
return nil, errors.New("cacheManager did not exist the reg function")
}