generated from inherelab/go-pkg-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
61 lines (52 loc) · 1.29 KB
/
util.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
package properties
import (
"reflect"
"regexp"
"strings"
"time"
"github.com/gookit/goutil/strutil"
"github.com/mitchellh/mapstructure"
)
// ValDecodeHookFunc returns a mapstructure.DecodeHookFunc that parse time string
func ValDecodeHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data any) (any, error) {
if f.Kind() != reflect.String {
return data, nil
}
str := data.(string)
ln := len(str)
if ln < 2 {
return str, nil
}
// start char is number(1-9) and end char is a-z.
if str[0] > '0' && str[0] < '9' && str[ln-1] > 'a' {
// parse time string. eg: 10s
if t.Kind() == reflect.Int64 {
dur, err := time.ParseDuration(str)
if err == nil {
return dur, nil
}
}
}
return str, nil
}
}
// eg: ${some.other.key} -> some.other.key
var refRegex = regexp.MustCompile(`^[a-z][a-z\d.]+$`)
func parseVarRefName(val string) (string, bool) {
if !strings.HasPrefix(val, VarRefStartChars) || !strings.HasSuffix(val, "}") {
return "", false
}
refName := val[2 : len(val)-1]
if refRegex.MatchString(refName) {
return refName, true
}
return "", false
}
func parseInlineSlice(s string, ln int) (ss []string, ok bool) {
// eg: [34, 56]
if s[0] == '[' && s[ln-1] == ']' {
return strutil.Split(s[1:ln-1], ","), true
}
return
}