Skip to content

WebAssembly

Dmitri Shuralyov edited this page Sep 16, 2018 · 53 revisions

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.

Example

To compile a basic Go package for the web:

package main

import "fmt"

func main() {
	fmt.Println("Hello, WebAssembly!")
}

Set GOOS=js and GOARCH=wasm environment variables to compile for WebAssembly:

$ GOOS=js GOARCH=wasm go build -o main.wasm

That will build the package and produce an executable WebAssembly module file main.wasm. The .wasm file extension will make it easier to serve it over HTTP with the correct Content-Type header later on. To execute main.wasm in a browser, we'll also need a JavaScript support file and an HTML page that connects everything together.

Copy the JavaScript support file:

$ cp $(go env GOROOT)/misc/wasm/wasm_exec.js .

Create an index.html file:

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="wasm_exec.js"></script>
		<script>
			const go = new Go();
			WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
				go.run(result.instance);
			});
		</script>
	</head>
	<body></body>
</html>

(If your browser doesn't yet support WebAssembly.instantiateStreaming, you can use a polyfill.)

Then serve those three files (index.html, wasm_exec.js, and main.wasm) to a web browser. For example, with goexec:

$ goexec 'http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))'

(Or use your own basic HTTP server command.)

Finally, navigate to http://localhost:8080/index.html, open the JavaScript debug console, and you should see the output. You can modify the program, rebuild main.wasm, and refresh to see new output.

Interacting with the DOM

See https://godoc.org/syscall/js.

Debugging

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:

Please get involved and help drive this if you're interested in the Debugger side of things. 😄

Tutorials + Articles

Further reference examples

Editor configuration

Clone this wiki locally