1

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

Baelfire18
  • 175
  • 2
  • 7

1 Answers1

1

The pure Go way is to mount the function on the JavaScript global object (usually window or global) with the syscall/js package:

js.Global().Set("myexport", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
    //stuff
})

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:

Uncaught Error: Go program has already exited

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:

package main

import (
    "fmt"
    "syscall/js"
)

func FuncName(M int, durations []int) int {
    fmt.Println("[GO] Log file.go", M, durations)
    return 10
}

func main() {
    fmt.Println("Hello, WebAssembly!")

    // Mount the function on the JavaScript global object.
    js.Global().Set("FuncName", js.FuncOf(func(this js.Value, args []js.Value) any {
        if len(args) != 2 {
            fmt.Println("invalid number of args")
            return nil
        }
        if args[0].Type() != js.TypeNumber {
            fmt.Println("the first argument should be a number")
            return nil
        }

        arg := args[1]
        if arg.Type() != js.TypeObject {
            fmt.Println("the second argument should be an array")
            return nil
        }

        durations := make([]int, arg.Length())
        for i := 0; i < len(durations); i++ {
            item := arg.Index(i)
            if item.Type() != js.TypeNumber {
                fmt.Printf("the item at index %d should be a number\n", i)
                return nil
            }
            durations[i] = item.Int()
        }

        // Call the actual func.
        return FuncName(args[0].Int(), durations)
    }))

    // Prevent the program from exiting.
    // Note: the exported func should be released if you don't need it any more,
    // and let the program exit after then. To simplify this demo, this is
    // omitted. See https://pkg.go.dev/syscall/js#Func.Release for more information.
    select {}
}

index.html:

<html>
  <head>
    <meta charset="utf-8" />
    <script src="wasm_exec.js"></script>
    <script>
      const go = new Go();
      WebAssembly.instantiateStreaming(
        fetch('main.wasm'),
        go.importObject
      ).then((result) => {
        go.run(result.instance);
      });
    </script>
  </head>
  <body>
    <button id="btn">Call FuncName</button>
    <script>
      document.getElementById('btn').addEventListener('click', () => {
        console.log(FuncName(1, [1, 2, 3, 4, 5]));
      });
    </script>
  </body>
</html>
Zeke Lu
  • 6,349
  • 1
  • 17
  • 23