You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.5 KiB
72 lines
1.5 KiB
package jsruntime
|
|
|
|
import (
|
|
"github.com/dop251/goja"
|
|
"github.com/dop251/goja_nodejs/console"
|
|
"github.com/dop251/goja_nodejs/eventloop"
|
|
"github.com/dop251/goja_nodejs/require"
|
|
"io/ioutil"
|
|
"time"
|
|
)
|
|
|
|
type JsRuntime struct {
|
|
MainSrc string
|
|
UseSrc string
|
|
Relys Relys
|
|
runtime *goja.Runtime
|
|
registry *require.Registry
|
|
requireModule *require.RequireModule
|
|
}
|
|
|
|
type Rely struct {
|
|
Variable string
|
|
FileName string
|
|
}
|
|
type Relys []Rely
|
|
|
|
func NewJsRuntime(mainFileName string, useFileName string, rels Relys) (*JsRuntime, error) {
|
|
jr := JsRuntime{
|
|
Relys: rels,
|
|
}
|
|
mainScript, err := ioutil.ReadFile(mainFileName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
jr.MainSrc = string(mainScript)
|
|
jr.registry = new(require.Registry) // this can be shared by multiple runtimes
|
|
loop := eventloop.NewEventLoop()
|
|
loop.Run(func(r *goja.Runtime) {
|
|
jr.runtime = r
|
|
})
|
|
|
|
jr.requireModule = jr.registry.Enable(jr.runtime)
|
|
console.Enable(jr.runtime)
|
|
|
|
for e := range rels {
|
|
v, err := jr.requireModule.Require(rels[e].FileName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
jr.runtime.Set(rels[e].Variable, v)
|
|
}
|
|
|
|
go func() {
|
|
for {
|
|
useSrc, _ := ioutil.ReadFile(mainFileName)
|
|
jr.UseSrc = string(useSrc)
|
|
time.Sleep(time.Second * 2)
|
|
}
|
|
}()
|
|
return &jr, nil
|
|
}
|
|
|
|
func (jr *JsRuntime) Render(tpl string) string {
|
|
jr.runtime.Set("HTML_SRC", tpl)
|
|
|
|
runtime.Set("HTML_OUT", func(data string) {
|
|
context.Writer.WriteHeader(200)
|
|
context.Writer.Write([]byte(data))
|
|
|
|
return
|
|
})
|
|
}
|