Go生成wasm初体验
背景
使用浏览器运行HelloWorld
编译
编译成wasm
GOOS=js GOARCH=wasm go build -o main.wasm
结果
./main.wasm
运行
准备
cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
编辑 index.html
文件:
<html> <head> <meta charset="utf-8"/> <script src="wasm_exec.js"></script> <script> const go = new Go(); WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => { go.run(result.instance); }); </script> </head> <body></body> </html>
安装 goexec
包
go get -u github.com/shurcooL/goexec
用 goexec
启动web服务
goexec 'http.ListenAndServe(`:9999`, http.FileServer(http.Dir(`.`)))'
运行结果
在浏览器控制台上,可以看到 "Hello World. "
使用Node.js运行HelloWorld
使用nodejs的好处是,测试和发布更方便。