forked from jiaoge/sjet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strings.go
83 lines (69 loc) · 1.94 KB
/
strings.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
package function
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"reflect"
"strings"
"github.com/CloudyKit/jet/v6"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
)
func init() {
globalFunc["md5"] = md5Func
globalFunc["base64"] = base64Func
globalFunc["base64Decode"] = base64DecodeFunc
globalFunc["substring"] = substringFunc
globalFunc["indexOf"] = indexOfFunc
globalFunc["lenStr"] = lenStrFunc
}
func substringFunc(a jet.Arguments) reflect.Value {
value := a.Get(0).Interface()
if a.Get(0).Type().Kind() == reflect.Float64 {
num := value.(float64)
prefix := int32(a.Get(1).Interface().(float64))
val, _ := decimal.NewFromFloat(num).Round(prefix).Float64()
return reflect.ValueOf(val)
} else {
str := value.(string)
strs := []rune(str)
start := int32(0)
end := int32(a.Get(1).Interface().(float64))
if a.NumOfArguments() == 3 {
start = int32(a.Get(1).Interface().(float64))
end = int32(a.Get(2).Interface().(float64))
}
return reflect.ValueOf(string(strs[start:end]))
}
}
func lenStrFunc(a jet.Arguments) reflect.Value {
value := a.Get(0).Interface()
strs := []rune(value.(string))
return reflect.ValueOf(float64(len(strs)))
}
func indexOfFunc(a jet.Arguments) reflect.Value {
value := a.Get(0).Interface().(string)
key := a.Get(1).Interface().(string)
return reflect.ValueOf(strings.Index(value, key))
}
func md5Func(a jet.Arguments) reflect.Value {
str := a.Get(0).Interface().(string)
h := md5.New()
h.Write([]byte(str))
val := hex.EncodeToString(h.Sum(nil))
return reflect.ValueOf(val)
}
func base64Func(a jet.Arguments) reflect.Value {
str := a.Get(0).Interface().(string)
b := []byte(str)
sEnc := base64.StdEncoding.EncodeToString(b)
return reflect.ValueOf(sEnc)
}
func base64DecodeFunc(a jet.Arguments) reflect.Value {
str := a.Get(0).Interface().(string)
sDec, err := base64.StdEncoding.DecodeString(str)
if err != nil {
logrus.Error(err, str)
}
return reflect.ValueOf(sDec)
}