Home > database >  How to use Fetch in JavaScript (V8go, Otto) in Golang?
How to use Fetch in JavaScript (V8go, Otto) in Golang?

Time:07-07

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?

CodePudding user response:

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.

  • Related