MCPcopy Index your code
hub / github.com/expr-lang/expr / ExampleWithContext

Function ExampleWithContext

expr_test.go:639–678  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

637}
638
639func 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
680func ExampleTimezone() {
681 program, err := expr.Compile(`now().Location().String()`, expr.Timezone("Asia/Kamchatka"))

Callers

nothing calls this directly

Calls 5

CompileFunction · 0.92
EnvStruct · 0.92
WithContextFunction · 0.92
RunFunction · 0.92
PrintfMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…