wa-lang.org/wazero@v1.0.2/imports/wasi_snapshot_preview1/example_test.go (about) 1 package wasi_snapshot_preview1 2 3 import ( 4 "context" 5 _ "embed" 6 "fmt" 7 "log" 8 "os" 9 10 "wa-lang.org/wazero" 11 "wa-lang.org/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 31 // Instantiate WASI, which implements system I/O such as console output. 32 wm, err := Instantiate(ctx, r) 33 if err != nil { 34 log.Panicln(err) 35 } 36 defer wm.Close(testCtx) 37 38 // Compile the WebAssembly module using the default configuration. 39 code, err := r.CompileModule(ctx, exitOnStartWasm) 40 if err != nil { 41 log.Panicln(err) 42 } 43 defer code.Close(ctx) 44 45 // InstantiateModule runs the "_start" function which is like a "main" function. 46 // Override default configuration (which discards stdout). 47 mod, err := r.InstantiateModule(ctx, code, wazero.NewModuleConfig().WithStdout(os.Stdout).WithName("wasi-demo")) 48 if mod != nil { 49 defer r.Close(ctx) 50 } 51 52 // Note: Most compilers do not exit the module after running "_start", unless 53 // there was an error. This allows you to call exported functions. 54 if exitErr, ok := err.(*sys.ExitError); ok { 55 fmt.Printf("exit_code: %d\n", exitErr.ExitCode()) 56 } 57 58 // Output: 59 // exit_code: 2 60 }