package gojs

import "github.com/tetratelabs/wazero/experimental/gojs"

Package gojs allows you to run wasm binaries compiled by Go when `GOOS=js` and `GOARCH=wasm`.

Usage

When `GOOS=js` and `GOARCH=wasm`, Go's compiler targets WebAssembly 1.0 Binary format (%.wasm).

Ex.

GOOS=js GOARCH=wasm go build -o cat.wasm .

After compiling `cat.wasm` with wazero.Runtime's `CompileModule`, Run it.

Under the scenes, the compiled Wasm calls host functions that support the runtime.GOOS. This is similar to what is implemented in wasm_exec.js. See https://github.com/golang/go/blob/go1.19/misc/wasm/wasm_exec.js

Experimental

Go defines js "EXPERIMENTAL... exempt from the Go compatibility promise." Accordingly, wazero cannot guarantee this will work from release to release, or that usage will be relatively free of bugs. Due to this and the relatively high implementation overhead, most will choose TinyGo instead.

Index

Functions

func Run

Run instantiates a new module and calls "run" with the given config.

Parameters

Example

After compiling your Wasm binary with wazero.Runtime's `CompileModule`, run it like below:

// Use compilation cache to reduce performance penalty of multiple runs.
ctx = experimental.WithCompilationCacheDirName(ctx, ".build")
// Execute the "run" function, which corresponds to "main" in stars/main.go.
err = gojs.Run(ctx, r, compiled, config)
if exitErr, ok := err.(*sys.ExitError); ok && exitErr.ExitCode() != 0 {
	log.Panicln(err)
} else if !ok {
	log.Panicln(err)
}

Notes

func WithRoundTripper

func WithRoundTripper(ctx context.Context, rt http.RoundTripper) context.Context

WithRoundTripper sets the http.RoundTripper used to Run Wasm.

For example, if the code compiled via `GOARCH=wasm GOOS=js` uses http.RoundTripper, you can avoid failures by assigning an implementation like so:

ctx = gojs.WithRoundTripper(ctx, http.DefaultTransport)
err = gojs.Run(ctx, r, compiled, config)

Source Files

gojs.go

Version
v1.0.0-beta.1
Published
Aug 30, 2022
Platform
linux/amd64
Imports
4 packages
Last checked
2 hours ago

Tools for package owners.