github.com/tetratelabs/wazero@v1.7.3-0.20240513003603-48f702e154b5/imports/wasi_snapshot_preview1/example_test.go (about) 1 package wasi_snapshot_preview1_test 2 3 import ( 4 "context" 5 _ "embed" 6 "fmt" 7 "os" 8 9 "github.com/tetratelabs/wazero" 10 "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" 11 "github.com/tetratelabs/wazero/sys" 12 ) 13 14 // exitOnStartWasm was generated by the following: 15 // 16 // cd testdata; wat2wasm --debug-names exit_on_start.wat 17 // 18 //go:embed testdata/exit_on_start.wasm 19 var exitOnStartWasm []byte 20 21 // This is an example of how to use WebAssembly System Interface (WASI) with its simplest function: "proc_exit". 22 // 23 // See https://github.com/tetratelabs/wazero/tree/main/examples/wasi for another example. 24 func Example() { 25 // Choose the context to use for function calls. 26 ctx := context.Background() 27 28 // Create a new WebAssembly Runtime. 29 r := wazero.NewRuntime(ctx) 30 defer r.Close(ctx) 31 32 // Instantiate WASI, which implements system I/O such as console output. 33 wasi_snapshot_preview1.MustInstantiate(ctx, r) 34 35 // InstantiateModule runs the "_start" function which is like a "main" function. 36 mod, err := r.InstantiateWithConfig(ctx, exitOnStartWasm, 37 // Override default configuration (which discards stdout). 38 wazero.NewModuleConfig().WithStdout(os.Stdout).WithName("wasi-demo")) 39 if mod != nil { 40 defer r.Close(ctx) 41 } 42 43 // Note: Most compilers do not exit the module after running "_start", unless 44 // there was an error. This allows you to call exported functions. 45 if exitErr, ok := err.(*sys.ExitError); ok { 46 fmt.Printf("exit_code: %d\n", exitErr.ExitCode()) 47 } 48 49 // Output: 50 // exit_code: 2 51 }