Go 1.11 之後的版本,支援可以直接將 Go 寫的內容編譯成 WebAssembly (wasm),然後搭配已經寫好的 wasm_exec.html 和 wasm_exec.js 就可以直接在頁面上執行。
- 註:WebAssembly 在 Firefox 52+ 和 Chrome 57+/latest Opera 是預設支持的
如何將 Go 程式編譯成 WebAssembly
Go 1.11 開始支援編譯成 WebAssembly,詳見:WebAssembly · golang/go Wiki · GitHub
使用 GVM 安裝 Go1.11
- gvm install go1.11
- gvm use go1.11
Go1.11 編譯出 wasm 步驟
- vim main.go # 下述範例都取自上述官方範例
package main func main() { println("Hello, WebAssembly!") }
- vim server.go
package mainimport ( "flag" "log" "net/http" "strings" ) 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) log.Fatal(http.ListenAndServe(*listen, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { if strings.HasSuffix(req.URL.Path, ".wasm") { resp.Header().Set("content-type", "application/wasm") } http.FileServer(http.Dir(*dir)).ServeHTTP(resp, req) }))) }
- GOARCH=wasm GOOS=js go build -o test.wasm main.go
- cp $(go env GOROOT)/misc/wasm/wasm_exec.{html,js} .
- 註:$(go env GOROOT) = ~/.gvm/gos/go1.11/misc/wasm/
- go run server.go
http://example.com:8080/wasm_exec.html - 點 RUN 打開 Console 就會出現 Hello, WebAssembly!
- Go 如何與 JavaScript 溝通(js.Value.*),可參考 syscall/js 函式庫,此篇有更多範例說明:Go 1.11: WebAssembly for the gophers
相關網頁
- WebAssembly Debugging Capabilities
- WebAssembly support lands in Go language: golang wasm/js
- WebAssembly | MDN
- Loading and running WebAssembly code - WebAssembly | MDN
- WebAssembly Archives - Mozilla Hacks - the Web developer blog
- Making WebAssembly even faster: Firefox’s new streaming and tiering compiler
- 使用WebAssembly JavaScript API - WebAssembly | MDN
- Go 1.11 and beyond: Go Northwest - Google Slides