WebAssembly获得了所有浏览器的一致支持, Chrome 和 Firefox 已经原生支持 WebAssembly,Edge 和 Safari 也在预览版中加入了 WebAssembly 支持。
Go很快也会对WebAssembly进行支持,目前还处理开发阶段。社区已经有对应的指导文档,下面就是社区的部分指导步骤。
”
Compiling Go code to wasm is also doable, but the support for this backend hasn’t been yet integrated into gc. An issue is tracking the progress of this feature: https://github.com/golang/go/issues/18892. As that discussion is quite long, here is the executive summary: a development branch with preliminary support for wasm has been created by @neelance (Richard Musiol) (yeah!).
Here are the instructions to compile a gc toolchain with a GOOS=js GOARCH=wasm environment:
$> cd somewhere
$> git clone https://go.googlesource.com/go
$> cd go
$> git remote add neelance https://github.com/neelance/go
$> git fetch --all
$> git checkout wasm-wip
$> cd src
$> ./make.bash
$> cd ../misc/wasm
The misc/wasm directory contains all the files (save the actual wasm module) to execute a wasm module with nodejs.
Let us compile the following main.go file:
package main
func main() {
println("Hello World, from wasm+Go")
}
with our new wasm-capable go binary:
$> GOARCH=wasm GOOS=js go build -o test.wasm main.go
$> ll
total 4.0K
-rw-r--r-- 1 binet binet 68 Dec 14 14:30 main.go
-rwxr-xr-x 1 binet binet 947K Dec 14 14:30 test.wasm
Copy over the misc/wasm files under this directory, and then finally, run the following server.go file:
package main
import (
"flag"
"log"
"net/http"
)
func main() {
addr := flag.String("addr", ":5555", "server address:port")
flag.Parse()
srv := http.FileServer(http.Dir("."))
log.Printf("listening on %q...", *addr)
log.Fatal(http.ListenAndServe(*addr, srv))
}
Like so:
$> ll
total 968K
-rw-r--r-- 1 binet binet 68 Dec 14 14:30 main.go
-rw-r--r-- 1 binet binet 268 Dec 14 14:38 server.go
-rwxr-xr-x 1 binet binet 947K Dec 14 14:30 test.wasm
-rw-r--r-- 1 binet binet 482 Dec 14 14:32 wasm_exec.html
-rwxr-xr-x 1 binet binet 7.9K Dec 14 14:32 wasm_exec.js
$> go run ./server.go
2017/12/14 14:39:18 listening on ":5555"...
Navigating to localhost:5555/wasm_exec.html will present you with a [Run] button that, when clicked should display “Hello World, from wasm+Go” in the console.
We’ve just had our browser run a wasm module, generated with our favorite compilation toolchain!
“
WebAssembly 的出现则提供了一个更好的选择:接近原生的运算效率,开源、兼容性好、平台覆盖广的标准,以及可以借此机会抛弃 JavaScript 的历史遗留问题。
欢迎加入我的微信公众号
有疑问加站长微信联系(非本文作者)