testotto.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import (
  3. "git.wecise.com/wecise/common/lib/robertkrimen/otto"
  4. "log"
  5. "reflect"
  6. )
  7. type ottoDemo struct {
  8. }
  9. func (demo *ottoDemo) resetVM(vm *otto.Otto) {
  10. // Reset vm custom properties
  11. value, _ := vm.Get("_defaultProperties_")
  12. if value.IsUndefined() {
  13. propertySet := make(map[string]bool)
  14. vm.GlobalForEach(func(name string) bool {
  15. propertySet[name] = true
  16. return true
  17. })
  18. propertySet["_defaultProperties_"] = true
  19. _ = vm.Set("_defaultProperties_", propertySet)
  20. } else {
  21. pv, _ := value.Export()
  22. propertySet := pv.(map[string]bool)
  23. vm.GlobalForEach(func(name string) bool {
  24. if _, ok := propertySet[name]; !ok {
  25. vm.Delete(name)
  26. }
  27. return true
  28. })
  29. }
  30. }
  31. func main() {
  32. log.SetFlags(log.LstdFlags | log.Lshortfile)
  33. demo := new(ottoDemo)
  34. vm := otto.New()
  35. // Custom js function
  36. logLib, _ := vm.Object(`log = {}`)
  37. _ = logLib.Set("info", func(call otto.FunctionCall) otto.Value {
  38. var v otto.Value
  39. v1 := call.Argument(0)
  40. if !v1.IsString() {
  41. panic(call.Otto.MakeCustomError("GoError:" + call.CallerLocation(), " incorrect parameter data type, should be: message<string>"))
  42. }
  43. msg, _ := v1.ToString()
  44. log.Println(msg)
  45. return v
  46. })
  47. _ = vm.Set("log", logLib)
  48. demo.resetVM(vm)
  49. _ = vm.Set("xyz", map[string]bool{"x":false, "y":false, "z":false})
  50. _, err := vm.Run(`
  51. abc = 2 + 2;
  52. console.log(xyz);
  53. console.log("The value of abc is " + abc); // 4
  54. log.info("Hello otto!");
  55. `)
  56. if err != nil {
  57. log.Fatal(err)
  58. }
  59. v, _ := vm.Get("abc")
  60. log.Println(v.ToInteger())
  61. v2, _ := vm.Get("xyz")
  62. ottoVal, _ := v2.Export()
  63. log.Println(reflect.TypeOf(ottoVal))
  64. demo.resetVM(vm)
  65. _, err = vm.Run(`log.info("Hello otto agin");console.log(abc);`)
  66. if err != nil {
  67. log.Fatal(err)
  68. }
  69. log.Println("exit")
  70. }