eval.go 865 B

1234567891011121314151617181920212223242526272829303132333435
  1. package tengo
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. )
  7. // Eval compiles and executes given expr with params, and returns an
  8. // evaluated value. expr must be an expression. Otherwise it will fail to
  9. // compile. Expression must not use or define variable "__res__" as it's
  10. // reserved for the internal usage.
  11. func Eval(
  12. ctx context.Context,
  13. expr string,
  14. params map[string]interface{},
  15. ) (interface{}, error) {
  16. expr = strings.TrimSpace(expr)
  17. if expr == "" {
  18. return nil, fmt.Errorf("empty expression")
  19. }
  20. script := NewScript([]byte(fmt.Sprintf("__res__ := (%s)", expr)))
  21. for pk, pv := range params {
  22. err := script.Add(pk, pv)
  23. if err != nil {
  24. return nil, fmt.Errorf("script add: %w", err)
  25. }
  26. }
  27. compiled, err := script.RunContext(ctx)
  28. if err != nil {
  29. return nil, fmt.Errorf("script run: %w", err)
  30. }
  31. return compiled.Get("__res__").Value(), nil
  32. }