Hi!
I’m currently looking into WebAssembly and figured Go would be more interesting then Rust, but I didn’t come very far before I hit a big wall.
It seems I for some reason is unable to use syscall/js. My first simple hello world example works fine, and I have other Go projects that run as well, so I’m quite sure my environment is ok. But as soon I try to work with the js-object it all breaks.
My HTML page looks like this:
<html>
<head>
<meta charset="utf-8">
<title>Go WebAssembly Demo</title>
</head>
<body>
<script src="wasm_exec.js"></script>
<script>
if (!WebAssembly.instantiateStreaming) { // polyfill
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then(async (result) => {
mod = result.module;
inst = result.instance;
await go.run(inst)
});
</script>
</body>
</html>
My Go code looks like this:
package main
import "syscall/js"
// import "syscall/js"
func add(i []js.Value) {
js.Global().Set("output", js.ValueOf(i[0].Int()+i[1].Int()))
println(js.ValueOf(i[0].Int() + i[1].Int()).String())
}
func subtract(i []js.Value) {
js.Global().Set("output", js.ValueOf(i[0].Int()-i[1].Int()))
println(js.ValueOf(i[0].Int() - i[1].Int()).String())
}
func registerCallbacks() {
js.Global().Set("add", js.NewCallback(add))
js.Global().Set("subtract", js.NewCallback(subtract))
}
func main() {
c := make(chan struct{}, 0)
println("WASM Go Initialized")
registerCallbacks()
<-c
}
I build this code with this command;
GOARCH=wasm GOOS=js go build -o lib.wasm main.go
The error I get in the browser when using syscall/js is:
Unhandled Promise Rejection: TypeError: this._inst.exports.getsp is not a function. (In 'this._inst.exports.getsp()', 'this._inst.exports.getsp' is undefined)
I don’t get any compile errors and go build produce a lib.wasm for me. All code that doesn’t include syscall/js works fine. What do I do wrong here?