已经安装Go 1.11及以上版本。
Getting Started
编辑main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, Go WebAssembly!")
}
把main.go build成WebAssembly(简写为wasm)二进制文件
GOOS=js GOARCH=wasm go build -o lib.wasm main.go
把JavaScript依赖拷贝到当前路径
cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
创建一个index.html文件,并引入wasm_exec.js文件,调用刚才build的lib.wasm
<html>
<head>
<meta charset="utf-8">
<script src="wasm_exec.js"></script>
<script>
const go = new Go();
WebAssembly.instantiateStreaming(fetch("lib.wasm"), go.importObject).then((result) => {
go.run(result.instance);
});
</script>
</head>
<body></body>
</html>
创建server.go监听8080端口,serve当前路径
package main
import (
"flag"
"log"
"net/http"
)
var (
listen = flag.String("listen", ":8080", "listen address")
dir = flag.String("dir", ".", "directory to serve")
)
func main() {
flag.Parse()
log.Printf("listening on %q...", *listen)
err := http.ListenAndServe(*listen, http.FileServer(http.Dir(*dir)))
log.Fatalln(err)
}
启动服务
go run server.go
在浏览器访问localhost:8080,打开浏览器console,就可以看到输出Hello, Go WebAssembly!
。
reference
有疑问加站长微信联系(非本文作者)