()
| 637 | } |
| 638 | |
| 639 | func ExampleWithContext() { |
| 640 | env := map[string]any{ |
| 641 | "fn": func(ctx context.Context, _, _ int) int { |
| 642 | // An infinite loop that can be canceled by context. |
| 643 | for { |
| 644 | select { |
| 645 | case <-ctx.Done(): |
| 646 | return 42 |
| 647 | } |
| 648 | } |
| 649 | }, |
| 650 | "ctx": context.TODO(), // Context should be passed as a variable. |
| 651 | } |
| 652 | |
| 653 | program, err := expr.Compile(`fn(1, 2)`, |
| 654 | expr.Env(env), |
| 655 | expr.WithContext("ctx"), // Pass context variable name. |
| 656 | ) |
| 657 | if err != nil { |
| 658 | fmt.Printf("%v", err) |
| 659 | return |
| 660 | } |
| 661 | |
| 662 | // Cancel context after 100 milliseconds. |
| 663 | ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*100) |
| 664 | defer cancel() |
| 665 | |
| 666 | // After program is compiled, context can be passed to Run. |
| 667 | env["ctx"] = ctx |
| 668 | |
| 669 | // Run will return 42 after 100 milliseconds. |
| 670 | output, err := expr.Run(program, env) |
| 671 | if err != nil { |
| 672 | fmt.Printf("%v", err) |
| 673 | return |
| 674 | } |
| 675 | |
| 676 | fmt.Printf("%v", output) |
| 677 | // Output: 42 |
| 678 | } |
| 679 | |
| 680 | func ExampleTimezone() { |
| 681 | program, err := expr.Compile(`now().Location().String()`, expr.Timezone("Asia/Kamchatka")) |
nothing calls this directly
no test coverage detected
searching dependent graphs…