最近写一个程序,接口返回的数据是js格式的,需要通过golang来解析js,so 找到了一个好用的库otto
使用起来简单,函数就三个
vm:=otto.New()vm.Run("js code")
demo实现golang和javascript的互相调用
demo1 输入javascript变量abc
demo2 调用javascript函数hello
demo3 javascript调用golang函数add
package main
import (
"fmt"
"github.com/robertkrimen/otto"
)
func main() {
fmt.Println("1.print javascript variables")
vm := otto.New()
vm.Run(`
abc = 2 + 2;
console.log("The value of abc is " + abc); // 4
`)
if value, err := vm.Get("abc"); err == nil {
if value_int, err := value.ToInteger(); err == nil {
fmt.Println(value_int)
}
}
fmt.Println("\n2.call javascript function")
vm.Run(`
function hello(name){
console.log('hello ' + name)
return 'OK'
}
`)
ret, _ := vm.Call("hello", nil, "zhangsan")
fmt.Println(ret)
fmt.Println("\n3.call go func")
vm.Set("add", func(call otto.FunctionCall) otto.Value {
fmt.Println("call from js")
arg1, _ := call.Argument(0).ToInteger()
arg2, _ := call.Argument(1).ToInteger()
result, _ := vm.ToValue(arg1 + arg2)
return result
})
vm.Run(`
sum = add(1,10);
console.log('sum: ' + sum);
`)
}