v8dispatcher is a Go package for communicating to and from Javascript running in V8.
It provides a message abstraction layer on top of the v8worker package which has been enhanced to support synchronous messaging. The v8dispatcher has a MessageDispatcher component that is used to dispatch MessageSend values to function calls, both in Go and in Javascript (no reflection).
Go
md := NewMessageDispatcher()
md.RegisterFunc("now",func(m MessageSend) (interface{},error) {
return time.Now(), nil
})
Javascript
var now = V8D.callReturn("","now");
This is the minimal example for which a simple function (no arguments) is registered and called from Javascript when loading the source like this:
Go
md.Worker().Load("example.js", `var now = V8D.callReturn("","now");`)
Javascript
function now() {
return new Date();
}
Go
md := NewMessageDispatcher()
now, _ := md.CallReturn("this","now")
Go
md := NewMessageDispatcher()
md.RegisterFunc("handleEvent",func(m MessageSend) (interface{},error) {
dataMap := m.Arguments[0].(map[string]interface{})
data := dataMap["data"]
...
return nil, nil
})
Javascript
V8D.call("","handleEvent", {"data": "some event data"});
Javascript
function handleEvent(data) {
...
}
Go
md := NewMessageDispatcher()
md.Call("this","handleEvent",map[string]interface{}{
"data" : "some event data",
})
Go
md := NewMessageDispatcher()
md.Set("shoeSize",42)
shoeSize, _ := md.Get("shoeSize")
Javascript
var shoeSize = this["shoeSize"]
To invoke Go methods from Javascript, you can register a value whoes type implements the MessageHandler
interface.
Go
type MusicPlayer struct {}
func (m MusicPlayer) Perform(m MessageSend) (interface{}, error) {
switch (m.Selector) {
case "start":
case "stop":
case "pause":
case "reset":
default: return nil , errors.New("unknown selector")
}
}
Register an instance of MusicPlayer
Go
player := MusicPlayer{}
md := NewMessageDispatcher()
md.Register("player", player)
Now you can use this from Javascript
Javascript
V8D.call("player","start");
(c) 2016, http://ernestmicklei.com. MIT License