Skip to content

Instantly share code, notes, and snippets.

@AchalaSB
Last active October 9, 2019 14:31
Show Gist options
  • Select an option

  • Save AchalaSB/e849f9ff2fd496a4fdd0d55254e947cf to your computer and use it in GitHub Desktop.

Select an option

Save AchalaSB/e849f9ff2fd496a4fdd0d55254e947cf to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"../runtime"
)
func main() {
r, err := runtime.NewRuntime("simple.wasm")
if err != nil { panic(err) }
result, err := r.Main()
if err != nil { panic(err) }
log.Println("got:", result)
}
package runtime
import (
wasm "github.com/wasmerio/go-ext-wasm/wasmer"
)
type Runtime struct {
vm wasm.Instance
}
func NewRuntime(fp string) (*Runtime, error) {
// Reads the WebAssembly module as bytes.
bytes, err := wasm.ReadBytes(fp)
if err != nil {
return nil, err
}
// Instantiates the WebAssembly module.
instance, err := wasm.NewInstance(bytes)
if err != nil {
return nil, err
}
return &Runtime{
vm: instance,
}, nil
}
func (r Runtime) Main() (wasm.Value, error) {
main, ok := r.vm.Exports["main"]
if !ok {
return wasm.Value{}, fmt.Errorf("can't find main function")
}
return main()
}
package runtime
import (
"io"
"net/http"
"os"
"path/filepath"
"testing"
)
const RUNTIME_WASM string = "../simple.wasm"
const RUNTIME_WASM_URL string = "https://github.com/xyz/target/wasm32-unknown-unknown/debug/simple.wasm?raw=true"
// getRuntimeBlob checks if the runtime wasm file exists and if not get it from github
func getRuntimeBlob() (n int64, err error) {
if Exists(RUNTIME_WASM) {
return 0, nil
}
out, err := os.Create(RUNTIME_WASM)
if err != nil {
return 0, err
}
defer out.Close()
resp, err := http.Get(RUNTIME_WASM_URL)
if err != nil {
return 0, err
}
defer resp.Body.Close()
n, err = io.Copy(out, resp.Body)
return n, err
}
// Exists reports whether the named file or directory exists.
func Exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func newRuntime(t *testing.T) (*Runtime, error) {
_, err := getRuntimeBlob()
if err != nil {
t.Fatalf("Fail: could not get wasm file")
}
fp, err := filepath.Abs(RUNTIME_WASM)
if err != nil {
t.Fatal("could not create filepath")
}
r, err := NewRuntime(fp)
if err != nil {
t.Fatal(err)
} else if r == nil {
t.Fatal("did not create new VM")
}
return r, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment