TIL: WASM with Go and run it inside browser

 
Enter 1-10 in the above box. It should output UUIDs.

Writing Go code

func main() {
  done := make(chan struct{}, 0)
  js.Global().Set("wasmGenerateUUIDs", js.FuncOf(generateUUIDs))
  <-done
}

func generateUUIDs(this js.Value, args []js.Value) any {
  if len(args) == 0 {
    return uuid.NewString()
  }
  count, err := strconv.Atoi(args[0].String())
  if err != nil {
    return "ERROR: invalid number"
  }
  if count > 10 {
    return "ERROR: too many"
  }
  uuids := make([]string, count)
  for i := 0; i < count; i++ {
    uuids[i] = uuid.NewString()
  }
  return strings.Join(uuids, "\n")
}

And compile to WASM:

GOOS=js GOARCH=wasm go build -o static/main.wasm cmd/wasm/main.go

Hello

Run it in the browser

Include wasm_exec.js provided by Go.

cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .

Create index.html:

<script src="/lib/wasm_exec.js"></script>
<script>
  const go = new Go();
  WebAssembly.instantiateStreaming(fetch("go/uuid.wasm"), go.importObject).then((result) => {
    go.run(result.instance);
});
</script>

And add JavaScript:

const output = wasmGenerateUUIDs(input$.value);
output$.innerHTML = output.replaceAll('\n', '<br>');

Author

I'm Oliver Nguyen. A software maker working mostly in Go and JavaScript. I enjoy learning and seeing a better version of myself each day. Occasionally spin off new open source projects. Share knowledge and thoughts during my journey. Connect with me on , , , and .

Back Back