github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/experimental/gojs/example/cat.go (about) 1 package main 2 3 import ( 4 "context" 5 "log" 6 "os" 7 "path" 8 "testing/fstest" 9 "time" 10 11 wazero "github.com/wasilibs/wazerox" 12 "github.com/wasilibs/wazerox/experimental/gojs" 13 ) 14 15 // main invokes Wasm compiled via `GOOS=js GOARCH=wasm`, which writes an input 16 // file to stdout, just like `cat`. 17 // 18 // This shows how to integrate a filesystem with wasm using gojs. 19 func main() { 20 // Read the binary compiled with `GOOS=js GOARCH=wasm`. 21 bin, err := os.ReadFile(path.Join("cat", "main.wasm")) 22 if err != nil { 23 log.Panicln(err) 24 } 25 26 // Choose the context to use for function calls. 27 ctx := context.Background() 28 29 // Create a new WebAssembly Runtime. 30 r := wazero.NewRuntime(ctx) 31 defer r.Close(ctx) // This closes everything this Runtime created. 32 33 // Compile the wasm binary to machine code. 34 start := time.Now() 35 guest, err := r.CompileModule(ctx, bin) 36 if err != nil { 37 log.Panicln(err) 38 } 39 compilationTime := time.Since(start).Milliseconds() 40 log.Printf("CompileModule took %dms", compilationTime) 41 42 // Instantiate the host functions needed by the guest. 43 start = time.Now() 44 gojs.MustInstantiate(ctx, r, guest) 45 instantiateTime := time.Since(start).Milliseconds() 46 log.Printf("gojs.MustInstantiate took %dms", instantiateTime) 47 48 fakeFilesystem := fstest.MapFS{"test.txt": {Data: []byte("greet filesystem\n")}} 49 50 // Create the sandbox configuration used by the guest. 51 guestConfig := wazero.NewModuleConfig(). 52 // By default, I/O streams are discarded and there's no file system. 53 WithStdout(os.Stdout).WithStderr(os.Stderr). 54 WithFS(fakeFilesystem). 55 WithArgs("gojs", os.Args[1]) // only what's in the filesystem will work! 56 57 // Execute the "run" function, which corresponds to "main" in stars/main.go. 58 start = time.Now() 59 err = gojs.Run(ctx, r, guest, gojs.NewConfig(guestConfig)) 60 runTime := time.Since(start).Milliseconds() 61 log.Printf("gojs.Run took %dms", runTime) 62 if err != nil { 63 log.Panicln(err) 64 } 65 }