Hi I want to make a compile a GO file intro WASM and run in from a node server.
In the index.html i have this:
<script src="./path_to/wasm_exec.js" ></script>
<script>
const go = new Go();
WebAssembly.instantiateStreaming(fetch("./path_to/file.wasm"), go.importObject).then((result) => {
go.run(result.instance);
console.log(result);
console.log(go);
});
The GO file I compile to WASM is like this one:
package main
import (
"fmt"
)
//export FuncName
func FuncName(M int, durations []int) int {
fmt.Println("[GO] Log file.go", M, durations)
return 10
}
func main() {
fmt.Println("HELLO GO")
}
And I compile Im currently compiling using this:
GOOS=js GOARCH=wasm go build -o path_to/file.wasm path_to/file.go
I want to use the funtion FuncName outside the Go file, and inside the html but i can export it.
I tried using tinygo like this: `tinygo build -o path_to/file.wasm path_to/file.go``but it didint work neather
The pure Go way is to mount the function on the JavaScript global object (usually
windoworglobal) with thesyscall/jspackage:And to make the exported function always available on the page, the Go program should not exit. Otherwise, you will get this JavaScript error when calling the exported function:
See also wasm: re-use //export mechanism for exporting identifiers within wasm modules and Go WASM export functions.
Here is updated demo that works (compiled with
GOOS=js GOARCH=wasm go build -o main.wasm):main.go:
index.html: