goja_nodejs
goja_nodejs copied to clipboard
Add http module
I would like to know if I can work on the http module:
An example:
package main
import (
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/console"
"github.com/dop251/goja_nodejs/http"
"github.com/dop251/goja_nodejs/require"
)
func main() {
registry := new(require.Registry)
runtime := goja.New()
registry.Enable(runtime)
http.Enable(runtime)
console.Enable(runtime)
runtime.RunString(`
var data = http.get("https://www.google.com");
console.log(data);
`)
}
I am trying to do something like:
package http
import (
"io"
"net/http"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/require"
)
const ModuleName = "http"
type HttpModule struct {
runtime *goja.Runtime
}
func Get(url string) (string, error) {
res, err := http.Get(url)
if err != nil {
return "", err
}
data, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
body := string(data)
return body, nil
}
func (h *HttpModule) get(call goja.FunctionCall) goja.Value {
res, err := Get(call.Argument(0).String())
if err != nil {
if _, ok := err.(*goja.Exception); !ok {
panic(h.runtime.NewGoError(err))
}
panic(err)
}
ret := h.runtime.ToValue(res)
return ret
}
func Require(runtime *goja.Runtime, module *goja.Object) {
h := &HttpModule{
runtime: runtime,
}
exports := module.Get("exports").(*goja.Object)
exports.Set("get", h.get)
}
func Enable(runtime *goja.Runtime) {
runtime.Set("http", require.Require(runtime, ModuleName))
}
func init() {
require.RegisterCoreModule(ModuleName, Require)
}
It's a start. If I am authorized I can start working on this and submit a PR.