0

I am trying to run JavaScript inside of a Golang function, and use fetch to fetch JSON via APIs in the Javascript context.

I tried it in Otto with the following code:

import "github.com/robertkrimen/otto"
    vm := otto.New()
    vm.Run(`
    function tryfunc() {
        console.log("Started");
        fetch('https://www.example.com/APIendpoint');
        console.log("Success");
    }
    tryfunc();
    `)

Otto is very simple to use, but looks like Otto is an event bus and does not manage fetch.

I am now trying with v8go with the following code:

import v8 "rogchap.com/v8go"
ctx := v8.NewContext()
ctx.RunScript(`fetch("https://www.example.com/APIendpoint"), ""`)

but it requires another argument. The documentation is very unclear and is difficult to understand how to run even the simplest JS script.

Can someone help?

Filippo
  • 83
  • 9
  • `fetch` is a bit more complicated than what you seem to assume in your code. The main issue will be, I think, that `fetch` is asynchronous. See [Using the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). – Ouroborus Jul 05 '22 at 16:38
  • @Ouroborus I did write ```fetch``` without ```await``` to simplify the question. Anyhow, just using it as in JS would not work. – Filippo Jul 06 '22 at 09:51

1 Answers1

1

Otto and v8 implements ECMAScript and as of current 13.0 version doesn't require a builtin function fetch (See: https://262.ecma-international.org/13.0/#sec-function-properties-of-the-global-object), this function is implemented by web browsers.

I believe the second argument is simply a file name to prefix debug output (eg: foo.js:14: undefined bar), that's very usual in interpreters.

I suspect your script did ran, if you print out the output from RunScript (you're ignore both return values, a JavaScript value and an error), that should have an "undefined function fetch" and value nil. FYI there is an example for implementing fetch in v8go documentation.

Wagner Riffel
  • 302
  • 1
  • 3
  • Thank you for your comment. My aim was in fact to run frontend code (that runs on browsers) in the backend. I would not try to use JS in Golang otherwise. In the end it was simpler just to fetch in Golang. – Filippo Jul 06 '22 at 09:55