Created
July 8, 2019 17:56
-
-
Save tom-code/c958768276d3395a345552157cc1c04b to your computer and use it in GitHub Desktop.
test/demo how to use otto /go javascript interpreter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/robertkrimen/otto" | |
) | |
type Svc struct { | |
Name string | |
State bool | |
} | |
type V1 struct { | |
Field1 string | |
Svcs []Svc | |
} | |
func main() { | |
vm := otto.New() | |
vm.Set("f2", func(call otto.FunctionCall) otto.Value { | |
f := func() {fmt.Println("eeeee")} | |
o, _ := vm.ToValue(f) | |
return o | |
}) | |
vm.Set("f3", func(call otto.FunctionCall) otto.Value { | |
fmt.Println(call.Argument(0)) | |
fmt.Println(call.Argument(0).Object().Keys()) | |
o, _ := call.Argument(0).Object().Get("1") | |
o2, _ := o.Object().Get("abc") | |
fmt.Println(o2.String()) | |
v, _ := vm.Object(`[{"g":"ff"}]`) | |
return v.Value() | |
}) | |
vm.Set("f1", func(call otto.FunctionCall) otto.Value { | |
fmt.Printf("%s\n", call.Argument(0).String()) | |
v := V1 { | |
Field1: "zzz", | |
Svcs: []Svc { | |
{Name: "a1", State: true}, | |
{Name: "a2", State: false}, | |
}, | |
} | |
vo, err := vm.ToValue(v) | |
if err != nil { | |
fmt.Println(err) | |
panic(err) | |
} | |
return vo | |
}) | |
_, err := vm.Run(` | |
console.log("abc") | |
x = f1("testname") | |
console.log(x) | |
console.log(x.Field1) | |
console.log(x.Svcs) | |
x.Svcs.forEach( function(val, index) { | |
console.log(val.Name) | |
console.log(val.State) | |
}) | |
f = f2() | |
f() | |
str = [{"abc": "123"}] | |
str.push({"abc": "555"}) | |
m = f3(str) | |
console.log(m[0]["g"]) | |
`) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment