v8go
从Go执行JavaScript
V8依赖
V8版本:7.6.303.31
为了使其v8go可用作标准Go包,可以为Linux和OSX包含预构建的V8静态库。
V8需要64位,因此无法在32位系统上运行。
用法
import "rogchap.com/v8go"
运行脚本
ctx, _ := v8go.NewContext(nil) // creates a new V8 context with a new Isolate aka VM
ctx.RunScript("const add = (a, b) => a + b", "math.js") // executes a script on the global context
ctx.RunScript("const result = add(3, 4)", "main.js") // any functions previously added to the context can be called
val, _ ctx.RunScript("result", "value.js") // return a value in JavaScript back to Go
fmt.Printf("addition result: %s", val)
一个VM,很多情况
vm, _ := v8go.NewIsolate() // creates a new JavaScript VM
ctx1, _ := v8go.NewContext(vm) // new context within the VM
ctx1.RunScript("const multiply = (a, b) => a * b", "math.js")
ctx2, _ := v8go.NewContext(vm) // another context on the same VM
if _, err := ctx2.RunScript("multiply(3, 4)", "main.js"); err != nil {
// this will error as multiply is not defined in this context
}
Javascript错误
val, err := ctx.RunScript(src, filename)
if err != nil {
err = err.(v8go.JSError) // JavaScript errors will be returned as the JSError struct
fmt.Println(err.Message) // the message of the exception thrown
fmt.Println(err.Location) // the filename, line number and the column where the error occured
fmt.Println(err.StackTrace) // the full stack trace of the error, if available
fmt.Printf("javascript error: %v", err) // will format the standard error message
fmt.Printf("javascript stack trace: %+v", err) // will format the full error stack trace
}
更多使用文档可以看官方资料
开源地址:
由于头条审核网址比较严,防止他们误会是推广,所以大家可以自行搜索下载
也可以关注我的头条号后给我发送 `v8go`,会自动把下载地址发送给你(做了关键字自动回复)
您知道哪些好用的小工具,欢迎评论分享,共同探讨学习
更多更优质的资讯,请关注我,你的支持会鼓励我不断分享更多更好的优质文章。
本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.sosokankan.com/article/1216646.html