-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
54 lines (44 loc) · 1.12 KB
/
example_test.go
File metadata and controls
54 lines (44 loc) · 1.12 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
package main_test
import (
"context"
"fmt"
"time"
"github.com/sonalys/gon"
"github.com/sonalys/gon/encoding"
)
func Example_functions() {
type Person struct {
Name string `gon:"name"`
Birthday time.Time `gon:"birthday"`
}
person := &Person{
Name: "Bob",
Birthday: time.Date(1992, 3, 24, 0, 0, 0, 0, time.UTC),
}
scope, err := gon.
NewScope().
WithValues(gon.Values{
"friend": gon.Literal(person),
"greet": gon.Literal(func(name string, birthday time.Time) string {
return fmt.Sprintf("Hello %s, your birthday is at %s", name, birthday)
}),
// Context is handled automatic by gon, if specified by the function literal.
"print": gon.Literal(func(ctx context.Context, message string) {
fmt.Println(message)
}),
})
if err != nil {
panic(err)
}
ruleStr := `call("print", call("greet", friend.name, friend.birthday))`
rule, err := encoding.Decode([]byte(ruleStr), encoding.DefaultExpressionCodex)
if err != nil {
panic(err)
}
_, err = scope.Compute(rule)
if err != nil {
panic(err)
}
// Output:
// Hello Bob, your birthday is at 1992-03-24 00:00:00 +0000 UTC
}