package main import ( "git.wecise.com/wecise/common/lib/robertkrimen/otto" "log" "reflect" ) type ottoDemo struct { } func (demo *ottoDemo) resetVM(vm *otto.Otto) { // Reset vm custom properties value, _ := vm.Get("_defaultProperties_") if value.IsUndefined() { propertySet := make(map[string]bool) vm.GlobalForEach(func(name string) bool { propertySet[name] = true return true }) propertySet["_defaultProperties_"] = true _ = vm.Set("_defaultProperties_", propertySet) } else { pv, _ := value.Export() propertySet := pv.(map[string]bool) vm.GlobalForEach(func(name string) bool { if _, ok := propertySet[name]; !ok { vm.Delete(name) } return true }) } } func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) demo := new(ottoDemo) vm := otto.New() // Custom js function logLib, _ := vm.Object(`log = {}`) _ = logLib.Set("info", func(call otto.FunctionCall) otto.Value { var v otto.Value v1 := call.Argument(0) if !v1.IsString() { panic(call.Otto.MakeCustomError("GoError:" + call.CallerLocation(), " incorrect parameter data type, should be: message")) } msg, _ := v1.ToString() log.Println(msg) return v }) _ = vm.Set("log", logLib) demo.resetVM(vm) _ = vm.Set("xyz", map[string]bool{"x":false, "y":false, "z":false}) _, err := vm.Run(` abc = 2 + 2; console.log(xyz); console.log("The value of abc is " + abc); // 4 log.info("Hello otto!"); `) if err != nil { log.Fatal(err) } v, _ := vm.Get("abc") log.Println(v.ToInteger()) v2, _ := vm.Get("xyz") ottoVal, _ := v2.Export() log.Println(reflect.TypeOf(ottoVal)) demo.resetVM(vm) _, err = vm.Run(`log.info("Hello otto agin");console.log(abc);`) if err != nil { log.Fatal(err) } log.Println("exit") }