-
Notifications
You must be signed in to change notification settings - Fork 18.1k
WebAssembly
Go 1.11 adds an experimental port to WebAssembly.
WebAssembly is described on its home page as:
WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.
This page will be updated over time with more information relevant to Go's support for WebAssembly.
Note, if you ever set the GOROOT
environment variable to an old Go SDK path, please remove this environment variable. This environment variable is not needed any more. Otherwise, the go build
command below will report error:
go tool compile: exit status 2
compile: unknown architecture "wasm"
To compile the basic Go program for the web:
package main
func main() {
println("Hello, WebAssembly!")
}
Run:
$ GOOS=js GOARCH=wasm go build -o test.wasm main.go
And copy over the HTML & JS support files:
$ cp $(go env GOROOT)/misc/wasm/wasm_exec.{html,js} .
Then serve those three files (wasm_exec.html
, wasm_exec.js
, and test.wasm
) to a web browser.
For a basic HTTP server:
package main
import (
"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)
})))
}
Now navigate to http://localhost:8080/wasm_exec.html, click "Run", and you should see the output in the JavaScript debug console.
See https://tip.golang.org/pkg/syscall/js/
WebAssembly doesn't yet have any support for debuggers, so you'll need to use the good 'ol println()
approach for now to display output on the JavaScript console.
An official WebAssembly Debugging Subgroup has been created to address this, with some initial investigation and proposals under way:
- WebAssembly Debugging Capabilities Living Standard (source code for the doc)
- DWARF for WebAssembly Target (source code for the doc)
Please get involved and help drive this if you're interested in the Debugger side of things. 😄
- GoWasm Experiments - Demonstrates working code for several common call types
-
Drawing simple 3D objects on the 2D canvas (source code)
- Displays wireframe solids on the 2d canvas, using basic matrix maths. Use wasd/keypad keys to rotate.
- Configuring GoLand for WebAssembly - Shows the exact steps needed for getting Wasm working in GoLand