-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathexample_test.go
83 lines (69 loc) · 1.27 KB
/
example_test.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 evalfilter
import "fmt"
// Example is a function which will filter a list of people, to return
// only those members who are above a particular age, via the use of
// a simple script.
func Example() {
//
// This is the structure our script will operate upon.
//
type Person struct {
Name string
Age int
}
//
// Here is a list of people.
//
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
//
// We'll run this script against each entry in the list
//
script := `
// Example filter - we only care about people over 30.
if ( Age > 30 ) { return true ; }
// Since we return false the caller will know to ignore people here.
return false;
`
//
// Create the evaluator
//
eval := New(script)
//
// Prepare the evaluator.
//
err := eval.Prepare()
if err != nil {
fmt.Printf("Failed to compile the code:%s\n", err.Error())
return
}
//
// Process each person.
//
for _, entry := range people {
//
// Call the filter
//
res, err := eval.Run(entry)
//
// Error-detection is important (!)
//
if err != nil {
panic(err)
}
//
// We only care about the people for whom the filter
// returned `true`.
//
if res {
fmt.Printf("%v\n", entry)
}
}
// Output:
// {Bob 31}
// {John 42}
}