WebAssembly Go Tutorial
Go compiles to WebAssembly with its standard toolchain. The build carries the whole Go runtime with it.
Add two numbers in Go
Go exposes a function to JavaScript through the js package. This one returns a sum.
package main
import "syscall/js"
func main() {
js.Global().Set("add", js.FuncOf(func(this js.Value, args []js.Value) any {
return args[0].Int() + args[1].Int()
}))
select {}
}Build it for the browser
Two settings pick the browser as the target.
GOOS=js GOARCH=wasm go build -o main.wasmBuild it with TinyGo
TinyGo targets small output for the same code.
tinygo build -o main.wasm -target wasmExample
const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes, {});
console.log("2 + 3 =", instance.exports.add(2, 3));
console.log("40 + 2 =", instance.exports.add(40, 2));
})();Key points
- Go is a language with a standard WebAssembly target.
- Use GOOS=js and GOARCH=wasm to target the browser.
- The standard build bundles the runtime, so a tiny program builds to about 1.7 MB.
- Use the wasm_exec.js glue file to load the module.
- TinyGo builds a much smaller module as an alternative.
- The demo module below is the same add function compiled from WAT.
- Go code becomes a module the browser can run.
In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 2 and 3 and logs the sum. Then it calls add with 40 and 2 and logs that sum.
Note
TinyGo builds small modules, but it supports less of Go than the standard toolchain.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What is the cost of the standard Go build?