|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "log" |
| 6 | + "os" |
| 7 | + |
| 8 | + quickjswasi "github.com/paralin/go-quickjs-wasi" |
| 9 | + "github.com/tetratelabs/wazero" |
| 10 | + "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" |
| 11 | + "github.com/tetratelabs/wazero/sys" |
| 12 | +) |
| 13 | + |
| 14 | +func main() { |
| 15 | + // Choose the context to use for function calls. |
| 16 | + ctx := context.Background() |
| 17 | + |
| 18 | + // Create a new WebAssembly Runtime. |
| 19 | + r := wazero.NewRuntime(ctx) |
| 20 | + defer r.Close(ctx) // This closes everything this Runtime created. |
| 21 | + |
| 22 | + // Configure the module with stdin, stdout, and stderr. |
| 23 | + config := wazero.NewModuleConfig(). |
| 24 | + WithStdin(os.Stdin). |
| 25 | + WithStdout(os.Stdout). |
| 26 | + WithStderr(os.Stderr) |
| 27 | + |
| 28 | + // Instantiate WASI, which implements system call APIs. |
| 29 | + // This is required for the Wasm module to print to the console. |
| 30 | + wasi_snapshot_preview1.MustInstantiate(ctx, r) |
| 31 | + |
| 32 | + // Instantiate the Wasm module with just the wasm filename as argument. |
| 33 | + // This will automatically run the "_start" function of the module. |
| 34 | + mod, err := r.InstantiateWithConfig(ctx, quickjswasi.QuickJSWASM, config.WithArgs(quickjswasi.QuickJSWASMFilename)) |
| 35 | + if err != nil { |
| 36 | + // Note: Most compilers do not exit the module after running "_start", |
| 37 | + // unless there was an error. This allows you to call exported functions. |
| 38 | + if exitErr, ok := err.(*sys.ExitError); ok && exitErr.ExitCode() != 0 { |
| 39 | + log.Panicf("exit_code: %d\n", exitErr.ExitCode()) |
| 40 | + } else if !ok { |
| 41 | + log.Panicln(err) |
| 42 | + } |
| 43 | + } |
| 44 | + _ = mod |
| 45 | +} |
0 commit comments