-
Notifications
You must be signed in to change notification settings - Fork 0
/
goja.go
83 lines (64 loc) · 1.45 KB
/
goja.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package goja
import (
"fmt"
"github.com/gogap/config"
"time"
crand "crypto/rand"
"encoding/binary"
"io/ioutil"
"math/rand"
"github.com/gogap/flow"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/console"
"github.com/dop251/goja_nodejs/require"
"github.com/gogap/context"
)
func init() {
flow.RegisterHandler("lang.javascript.goja", ExecuteJS)
}
func ExecuteJS(ctx context.Context, conf config.Configuration) (err error) {
src := conf.GetString("src")
if len(src) == 0 {
err = fmt.Errorf("src not set")
return
}
timeout := conf.GetTimeDuration("timeout", 10*time.Minute)
vm := newVM()
vm.Set("ctx", ctx)
vm.Set("conf", conf)
var data []byte
data, err = ioutil.ReadFile(src)
if err != nil {
return
}
var prg *goja.Program
prg, err = goja.Compile(src, string(data), false)
if err != nil {
return
}
if timeout > 0 {
time.AfterFunc(timeout, func() {
vm.Interrupt("timeout")
})
}
_, err = vm.RunProgram(prg)
if err != nil {
err = fmt.Errorf("execute goja script failure: %s\n%s\n", err.Error(), src)
return
}
return
}
func newRandSource() goja.RandSource {
var seed int64
if err := binary.Read(crand.Reader, binary.LittleEndian, &seed); err != nil {
panic(fmt.Errorf("Could not read random bytes: %v", err))
}
return rand.New(rand.NewSource(seed)).Float64
}
func newVM() *goja.Runtime {
vm := goja.New()
vm.SetRandSource(newRandSource())
new(require.Registry).Enable(vm)
console.Enable(vm)
return vm
}