-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathengine.go
More file actions
57 lines (45 loc) · 1.24 KB
/
engine.go
File metadata and controls
57 lines (45 loc) · 1.24 KB
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
package dsl
import (
"sync"
"github.com/Knetic/govaluate"
)
var defaultEngine *Engine
type Engine struct {
HelperFunctions map[string]govaluate.ExpressionFunction
ExpressionStore map[string]*govaluate.EvaluableExpression
exprmux sync.RWMutex
}
func NewEngine() (*Engine, error) {
engine := &Engine{
HelperFunctions: DefaultHelperFunctions,
ExpressionStore: make(map[string]*govaluate.EvaluableExpression),
}
return engine, nil
}
func (e *Engine) EvalExpr(expr string, vars map[string]interface{}) (interface{}, error) {
e.exprmux.Lock()
defer e.exprmux.Unlock()
compiled, err := govaluate.NewEvaluableExpressionWithFunctions(expr, e.HelperFunctions)
if err != nil {
return nil, err
}
e.ExpressionStore[expr] = compiled
return compiled.Evaluate(vars)
}
func (e *Engine) EvalExprFromCache(expr string, vars map[string]interface{}) (interface{}, error) {
compiled, ok := e.ExpressionStore[expr]
if !ok {
return e.EvalExpr(expr, vars)
}
return compiled.Evaluate(vars)
}
func EvalExpr(expr string, vars map[string]interface{}) (interface{}, error) {
if defaultEngine == nil {
var err error
defaultEngine, err = NewEngine()
if err != nil {
return nil, err
}
}
return defaultEngine.EvalExprFromCache(expr, vars)
}