值得期待:Go對WebAssmbly的完全支援
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:
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 的歷史遺留問題。
歡迎加入我的微信公眾號