WebAssembly
- Go course
- Expert
- Lesson 25/34
- 4 min
Learn Go's WASM target.
WebAssembly
WebAssembly (WASM) is a portable binary format that runs at near-native speed in browsers and other runtimes. Go code can compile to WASM, so the same business logic runs on both the server and in the browser.
GOOS=js GOARCH=wasm go build -o main.wasm
cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" .On the browser side wasm_exec.js provides the bridge the Go runtime needs.
WASI
To run outside the browser (Wasmtime, Wasmer, serverless platforms) Go 1.21 added the GOOS=wasip1 target. WASI offers a standard interface to system functions such as files and clocks:
GOOS=wasip1 GOARCH=wasm go build -o app.wasm
wasmtime app.wasmWith Go 1.24 the //go:wasmexport directive can export Go functions to the host.
Practice Portable logic
Write a pure function to be used both on the server and in WASM: kdv(fiyat float64) float64 adds 20% to the price. Print fmt.Printf("%.2f\n", kdv(100)).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func kdv(fiyat float64) float64 {
return fiyat * 1.2
}
func main() {
fmt.Printf("%.2f\n", kdv(100))
}Expected output
120.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is a Go WASM binary usually several MB?
- WASM can't be compressed
- The browser adds it
- Debugging can't be turned off
- The Go runtime (GC, scheduler) is included in the binary Correct answer
Explanation: Standard Go embeds the runtime in every binary; when a small WASM is needed TinyGo is preferred.
2 Target architecture
GOOS=js GOARCH=____ go build -o main.wasm
GOOS=js GOARCH=wasm go build -o main.wasm
Explanation: GOARCH=wasm targets the WebAssembly architecture; GOOS=js selects the browser environment.
3 Target and environment
| Term | Meaning |
|---|---|
GOOS=js |
Browser / Node.js |
GOOS=wasip1 |
WASI runtimes |
wasm_exec.js |
JS bridge |
//go:wasmexport |
Export a function |