package gojs

import "github.com/tetratelabs/wazero/imports/go"

Package gojs allows you to run wasm binaries compiled by Go when `GOARCH=wasm GOOS=js`. See https://wazero.io/languages/go/ for more.

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 Instantiate

func Instantiate(ctx context.Context, r wazero.Runtime) (api.Closer, error)

Instantiate instantiates the "go" module, used by `GOARCH=wasm GOOS=js`, into the runtime.

Notes

func MustInstantiate

func MustInstantiate(ctx context.Context, r wazero.Runtime)

MustInstantiate calls Instantiate or panics on error.

This is a simpler function for those who know the module "go" is not already instantiated, and don't need to unload it.

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")

// Instantiate the host functions used for each call.
gojs.MustInstantiate(r)

// 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)

Types

type FunctionExporter

type FunctionExporter interface {
	// ExportFunctions builds functions to export with a
	// wazero.HostModuleBuilder named "go".
	ExportFunctions(wazero.HostModuleBuilder)
}

FunctionExporter configures the functions in the "go" module used by `GOARCH=wasm GOOS=js`.

func NewFunctionExporter

func NewFunctionExporter() FunctionExporter

NewFunctionExporter returns a FunctionExporter object.

Source Files

gojs.go

Directories

PathSynopsis
imports/go/example
Version
v1.0.0-rc.1
Published
Mar 1, 2023
Platform
js/wasm
Imports
7 packages
Last checked
45 minutes ago

Tools for package owners.