Lab 10: WASM Architecture

Time: 60 minutes | Level: Architect | Docker: golang:1.22-alpine

Overview

WebAssembly in production with Go: GOOS=js GOARCH=wasm advanced patterns, TinyGo for smaller binaries, syscall/js DOM manipulation, Go→JS type bridge, WASM memory management, streaming WASM compilation, and WASM SIMD concepts.


Step 1: Basic Go WASM Module

//go:build js && wasm

package main

import (
	"fmt"
	"syscall/js"
)

func main() {
	fmt.Println("Go WASM initialized")

	// Expose functions to JavaScript
	js.Global().Set("goAdd", js.FuncOf(addHandler))
	js.Global().Set("goSort", js.FuncOf(sortHandler))
	js.Global().Set("goFibonacci", js.FuncOf(fibHandler))

	// Block forever (event loop style)
	// Use channel to prevent main from exiting
	done := make(chan struct{})
	js.Global().Set("goShutdown", js.FuncOf(func(_ js.Value, _ []js.Value) interface{} {
		close(done)
		return nil
	}))
	<-done
}

// Handler: arguments come from JS as []js.Value
func addHandler(_ js.Value, args []js.Value) interface{} {
	if len(args) != 2 {
		return js.Global().Get("Error").New("need exactly 2 arguments")
	}
	a := args[0].Int()
	b := args[1].Int()
	return a + b
}

func fibHandler(_ js.Value, args []js.Value) interface{} {
	if len(args) != 1 {
		return 0
	}
	n := args[0].Int()
	return fib(n)
}

func fib(n int) int {
	if n <= 1 {
		return n
	}
	return fib(n-1) + fib(n-2)
}

Step 2: syscall/js Type Bridge


Step 3: DOM Manipulation


Step 4: WASM Memory Management


Step 5: Streaming WASM Compilation


Step 6: TinyGo — Smaller WASM Binaries


Step 7: WASM Workers


Step 8: Capstone — WASM Binary Build

📸 Verified Output:

(Magic bytes 0061 736d = \0asm — valid WebAssembly binary header)


Summary

Feature
API
Notes

Build target

GOOS=js GOARCH=wasm

Standard Go toolchain

JS interop

syscall/js

Bidirectional type bridge

Function export

js.FuncOf(handler)

Call from JavaScript

Byte transfer

js.CopyBytesToJS/Go

Efficient bulk transfer

DOM access

js.Global().Get("document")

Full DOM API

Streaming

instantiateStreaming()

2× faster than ArrayBuffer

TinyGo

tinygo build -target wasm

25× smaller binaries

Worker

Web Worker + wasm_exec.js

Non-blocking execution

Last updated