Files
wazero/wasi/example_test.go
Crypt Keeper c4caa1ea9b Changes how examples are tested, and fixes ExitError bug (#468)
Before, we tested the examples/ directory using "ExampleXX", but this is
not ideal because it literally embeds the call to `main` into example
godoc output. This stops doing that for a different infrastructure.

This also makes sure there's a godoc example for both the main package
and wasi, so that people looking at https://pkg.go.dev see something and
also a link to our real examples directory.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-15 15:51:27 +08:00

49 lines
1.3 KiB
Go

package wasi
import (
"fmt"
"log"
"os"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/sys"
)
// This is an example of how to use WebAssembly System Interface (WASI) with its simplest function: "proc_exit".
//
// See https://github.com/tetratelabs/wazero/tree/main/examples/wasi for another example.
func Example() {
r := wazero.NewRuntime()
// Instantiate WASI, which implements system I/O such as console output.
wm, err := InstantiateSnapshotPreview1(r)
if err != nil {
log.Fatal(err)
}
defer wm.Close()
// Override default configuration (which discards stdout).
config := wazero.NewModuleConfig().WithStdout(os.Stdout)
// InstantiateModuleFromCodeWithConfig runs the "_start" function which is like a "main" function.
_, err = r.InstantiateModuleFromCodeWithConfig([]byte(`
(module
(import "wasi_snapshot_preview1" "proc_exit" (func $wasi.proc_exit (param $rval i32)))
(func $main
i32.const 2 ;; push $rval onto the stack
call $wasi.proc_exit ;; return a sys.ExitError to the caller
)
(export "_start" (func $main))
)
`), config.WithName("wasi-demo"))
// Print the exit code
if exitErr, ok := err.(*sys.ExitError); ok {
fmt.Printf("exit_code: %d\n", exitErr.ExitCode())
}
// Output:
// exit_code: 2
}