寫這篇文章的目的主要是試用下goja,同時golang 也有另外一個otto 的實現,都是很不錯的選擇,因為otto集成了underscore 感覺很不錯
所以打算給goja 也集成下,同時學習下使用
otto underscore 的使用
因為默認otto的代碼中已經包含了underscore,使用是很簡單的
import (
"github.com/robertkrimen/otto"
_ "github.com/robertkrimen/otto/underscore"
)
otto underscore 的大致原理解析
engine 核心還是加載script 內容,為了方便otto基於go-bindata 潛入資源到代碼中了,同時otto 也有一個類似npm 的require機制
goja underscore 特性的支持
因為goja提供了一個node 兼容的require 擴展,所以我們需要做的基本就和otto對於underscore的類似,同時因為goja沒有otto 那么方便
的機制,我們需要自己調整下加載資源的模式(為了方便,同時也使用了類似otto 的go-bindata機制,同時使用了goja require 的自定義加載模式)
參考代碼
資源加載基於go-bindata 提供的Asset 保證也本地資源文件一致,同時也方便軟件分發
生成go-bindata 的方式
安裝cli
go get -u github.com/go-bindata/go-bindata/
生成代碼
go-bindata dalong.js app.js underscore-min.js
js 代碼文件加載
registry := require.NewRegistryWithLoader(func(path string) ([]byte, error) {
return Asset(path)
})
為了方便使用定義了一個簡單的vm struct, 同時提供了一個init 方法,方便注入一些擴展(比如underscore)實際可以結合自己的場景調整
package main
import (
"fmt"
"github.com/dop251/goja"
)
// MyVM myjvm
type MyVM struct {
jsRuntime *goja.Runtime
script string
}
func (vm *MyVM) init() {
vm.jsRuntime.Set("login", func(name, password string) string {
return fmt.Sprintf("%s-%s", name, password)
})
// load underscore for global user
m, _ :=myrequire.Require("underscore-min.js")
vm.jsRuntime.Set("_", m)
}
// Exec script
func (vm *MyVM) Exec() (goja.Value, error) {
return vm.jsRuntime.RunString(vm.script)
}
為了方便在使用的時候直接就用引用underscore 暴露的操作能力,我們直接使用了init 函數方便自動加載
package main
import (
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/require"
)
var (
myvm MyVM
myrequire *require.RequireModule
)
func init() {
// registry := new(require.Registry)
// use custom srcloader
registry := require.NewRegistryWithLoader(func(path string) ([]byte, error) {
return Asset(path)
})
myvm = MyVM{
jsRuntime: goja.New(),
script: `require("dalong.js")("dalong","ddddd")`,
}
myrequire = registry.Enable(myvm.jsRuntime)
myvm.init()
}
使用
- 入口
package main
import (
"fmt"
"log"
)
func main() {
value, _ := myvm.Exec()
fmt.Println(value)
m, err := myrequire.Require("app.js")
if err != nil {
log.Panic(err)
} else {
ob := m.ToObject(myvm.jsRuntime)
fmt.Print(ob.Get("filteruser").String())
}
}
app.js 說明
加載dalong.js模塊,同時使用underscore
var dalong = require("dalong.js")
var users = [
{
name:"dalong",
age:333
},
{
name:"rong",
age:22
},
{
name:"mydemo",
age:44
}
]
var evens = _.filter(users, function(user){ return user.age % 2 == 0; });
module.exports = {
version:"v1",
type_info:"system",
token: dalong("dalong","demoapp"),
filteruser: JSON.stringify(evens)
}
- 運行效果
說明
以上是一個簡單的給予goja 引入三方npm 模塊的一個嘗試,實際使用的時候我們可以會依賴一些三方依賴,解決方法:
就用browserify 打包依賴的npm 模塊,同時基於ffi模式運行,同時在結合go-bindata 基本就可以搞定了,后邊寫一個簡單的
demo,驗證下方案的可行性
參考資料
https://github.com/rongfengliang/goja-require-learning
https://github.com/dop251/goja
https://github.com/dop251/goja_nodejs
https://github.com/robertkrimen/otto
https://www.npmjs.com/package/browserify