/
util.go
77 lines (64 loc) · 1.53 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package expression
import (
"encoding/json"
"strconv"
"strings"
)
// GetLiteral return the literal value if it is a literal
func GetLiteral(strVal string) (interface{}, bool) {
newStrVal := strings.TrimSpace(strVal)
var val interface{}
var err error
//check if is integer
val, err = strconv.Atoi(newStrVal)
if err == nil {
return val, true
}
//check if is float
val, err = strconv.ParseFloat(newStrVal, 64)
if err == nil {
return val, true
}
//check if is string
s, isStr := isQuotedString(newStrVal)
if isStr {
return s, true
}
//check for booleans
if strings.EqualFold(newStrVal, "false") {
return false, true
}
if strings.EqualFold(newStrVal, "true") {
return true, true
}
//check if is object or array
var js interface{}
err = json.Unmarshal([]byte(newStrVal), &js)
if err == nil {
return js, true
}
return nil, false
}
func isQuotedString(newStrVal string) (string, bool) {
//String must surround with quotes and only one pair
if newStrVal[0] == '"' {
newStrVal = newStrVal[1:]
if len(newStrVal) == strings.Index(newStrVal, `"`)+1 {
return newStrVal[:len(newStrVal)-1], true
}
return "", false
} else if newStrVal[0] == '\'' {
newStrVal = newStrVal[1:]
if len(newStrVal) == strings.Index(newStrVal, `'`)+1 {
return newStrVal[:len(newStrVal)-1], true
}
return "", false
} else if newStrVal[0] == '`' {
newStrVal = newStrVal[1:]
if len(newStrVal) == strings.Index(newStrVal, "`")+1 {
return newStrVal[:len(newStrVal)-1], true
}
return "", false
}
return "", false
}