// NewMessageDispatcher returns a new MessageDispatcher initialize with empty handlers and a v8worker. func NewMessageDispatcher() *MessageDispatcher { d := &MessageDispatcher{ messageHandlerFuncs: map[string]MessageSendHandlerFunc{}, messageHandlers: map[string]MessageSendHandler{}, traceEnabled: false, } w := v8worker.New(d.Receive, d.ReceiveSync) d.worker = w // load scripts for _, each := range []struct { name string source string }{ {"registry.js", registry_js()}, {"setup.js", setup_js()}, {"console.js", console_js()}, } { if err := w.Load(each.name, each.source); err != nil { Log("error", "script load error", "source", each.name, "err", err) } } // install default console handling d.RegisterFunc("console.log", ConsoleLog) return d }
func runWorker(in <-chan message) <-chan message { out := make(chan message) go func() { worker := v8worker.New(func(msg string) { var message message if err := json.Unmarshal([]byte(msg), &message); err == nil { out <- message } }, DiscardSendSync) file, _ := ioutil.ReadFile("handle-json.js") worker.Load("handle-json.js", string(file)) for m := range in { bytes, err := json.Marshal(m) if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) } msg := string(bytes) if err := worker.Send(msg); err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) } } close(out) worker.TerminateExecution() }() return out }
//NewRPC makes RPC Server func NewRPC() *RPC { rpc := &RPC{ callbacks: map[string]func(interface{}){}, objects: map[string]interface{}{}, contexts: map[string]map[string]interface{}{}, } rpc.worker = v8worker.New(rpc.Recv) return rpc }
func newWorker(pool *workerPool, fn func(*Worker)) *Worker { w := new(Worker) v8w := v8worker.New(func(msg string) { w.ch <- msg }) w.Worker = v8w fn(w) return w }
func runWorker(done <-chan struct{}, scriptFile string) <-chan string { out := make(chan string) go func() { worker := v8worker.New(func(msg string) { out <- msg }, func(msg string) string { m := module{Id: msg, main: false} m.load() bytes, _ := json.Marshal(m) return string(bytes) }) defer func() { close(out) worker.TerminateExecution() }() if err := worker.Load("native-module.js", nativeModule); err != nil { log.Println(err) return } if err := loadMainModule(worker, scriptFile); err != nil { log.Println(err) return } for { select { case <-done: log.Println("killing worker...") return default: } } }() return out }