go1.11 wasm helloworld

时间:2022-11-22 11:57:35


go 1.11 版本中已经支持了对go程编译出web可执行的wasm文件,向js的强悍地位提出了挑战。
试水:
1.新建main.go

package main
import (
"fmt"
)

func main() {
fmt.Println("hello,wasm")
}

2.交叉编译成web可执行的二进制文件
该文件路径下,右键-git bash here,须安装git for windows

GOOS=js GOARCH=wasm go build -o main.wasm
  1. 新建index.html,与main.go同级目录:
<!doctype 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>

<!doctype 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>
  1. Go()这个对象位于wasm_exec.js, 这个文件位于 $GOROOT\misc\wasm
  2. 文件分布:
  3. go1.11  wasm helloworld

  4. git bash here,输入 node wasm_exec.js main.wasm
  5. go1.11  wasm helloworld