/
evaluate.go
58 lines (50 loc) · 1.4 KB
/
evaluate.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
package context
import (
"encoding/json"
"fmt"
"strings"
jmespath "github.com/jmespath/go-jmespath"
)
//Query the JSON context with JMESPATH search path
func (ctx *Context) Query(query string) (interface{}, error) {
query = strings.TrimSpace(query)
if query == "" {
return nil, fmt.Errorf("invalid query (nil)")
}
var emptyResult interface{}
// check for white-listed variables
if !ctx.isBuiltInVariable(query) {
return emptyResult, fmt.Errorf("variable %s cannot be used", query)
}
// compile the query
queryPath, err := jmespath.Compile(query)
if err != nil {
ctx.log.Error(err, "incorrect query", "query", query)
return emptyResult, fmt.Errorf("incorrect query %s: %v", query, err)
}
// search
ctx.mutex.RLock()
defer ctx.mutex.RUnlock()
var data interface{}
if err := json.Unmarshal(ctx.jsonRaw, &data); err != nil {
ctx.log.Error(err, "failed to unmarshal context")
return emptyResult, fmt.Errorf("failed to unmarshall context: %v", err)
}
result, err := queryPath.Search(data)
if err != nil {
ctx.log.Error(err, "failed to search query", "query", query)
return emptyResult, fmt.Errorf("failed to search query %s: %v", query, err)
}
return result, nil
}
func (ctx *Context) isBuiltInVariable(variable string) bool {
if len(ctx.builtInVars) == 0 {
return true
}
for _, wVar := range ctx.builtInVars {
if strings.HasPrefix(variable, wVar) {
return true
}
}
return false
}