Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Created February 18, 2023 12:48
Show Gist options
  • Save salrashid123/02940fc66c49f323aa25cd52d4407ae6 to your computer and use it in GitHub Desktop.
Save salrashid123/02940fc66c49f323aa25cd52d4407ae6 to your computer and use it in GitHub Desktop.
Load and run wasm in go with wasmer
package main
/*
$ cat helloworld.ts
export function add(a: i32, b: i32): i32 {
return a + b;
}
$ npm install -g assemblyscript
$ asc helloworld.ts -o hello-world.wasm
$ go run main.go
*/
import (
"fmt"
"io/ioutil"
wasmer "github.com/wasmerio/wasmer-go/wasmer"
)
func main() {
// use TEE attestation token here to download `hello-world.wasm`
wasmBytes, err := ioutil.ReadFile("hello-world.wasm")
if err != nil {
panic(err)
}
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
// Compiles the module
module, err := wasmer.NewModule(store, wasmBytes)
if err != nil {
panic(err)
}
// Instantiates the module
importObject := wasmer.NewImportObject()
instance, err := wasmer.NewInstance(module, importObject)
if err != nil {
panic(err)
}
// Gets the `add` exported function from the WebAssembly instance.
add, err := instance.Exports.GetFunction("add")
if err != nil {
panic(err)
}
// Calls that exported function with Go standard values. The WebAssembly
// types are inferred and values are casted automatically.
result, err := add(1, 5)
if err != nil {
panic(err)
}
fmt.Println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment