Golang 嵌入运行 JS、TS 语言

#

最近,由于业务需求,我们考虑在 Go 语言中嵌入其他脚本语言以实现功能的扩展,经过一番深入的调研之后,我们最终在 Lua 和 JS 之间做出了选择,最终选择了 JS,因为 JS 更容易上手。

目前社区有 Otto、Goja、V8 三种方案,其中性能最高的是 V8,但是使用这种方案需要使用 CGO,而且不是密集计算任务,其实纯 Go 实现的 Goja 性能也不会差到哪里去,但是 Goja 只支持 ES5 语法,并且默认没有超时之类的功能,因此为了方便使用,我们基于它进行了一定程度的封装。

配置项

js.New(func(o *js.Option) {           // 非必须
        o.Timeout = time.Minute * 3       // 脚本执行最长时间
        o.Dir = zfile.RealPath(".")       // 脚本文件目录
        o.Args = map[string]interface{}{} // 传入参数
        o.DisabledConsole = true          // 禁用控制台输出
        o.MaxPrograms = 1 << 10           // 最大缓存预处理脚本数量
})

简单例子

package main

import (
    "github.com/sohaha/zlsgo/zlog"
    "github.com/zlsgo/js"
)

func main() {
    js := js.New()
    res, err := js.Run([]byte(`const m = 1;m`))
    if err != nil {
        zlog.Error("执行失败", err)
        return
    }
    zlog.Debug("执行结果", res)
}

执行 typescript 也是可以的

package main

import (
    "github.com/sohaha/zlsgo/zlog"
    "github.com/zlsgo/js"
)

func main() {
    vm := js.New()

    res, err := vm.RunFileForMethod("./method.ts","run", "typescritp")

    zlog.Debug("执行结果", res, err) // hello typescritp
}
// method.ts
const m = 1

function run(name: string) {
    return `hello ${name}`
}

Github: github.com/zlsgo/js
文档: docs.73zls.com/zlsgo/#/e6526de5-3a...

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!