Golang WebAssembly Getting Started
Golang introduced WebAssembly support in version 1.11, which means that you can later use go to write a program that you can run in a browser, which is certainly bound by the browser sandbox environment.
1. Run Go1.1 code in the browser
package mainfunc main() { println("Hello, WebAssembly!")}
1.2 Compiling
It must be go1.11.
GOARCH=wasm GOOS=js go build -o test.wasm main.go
1.3 Run
A separate wasm file cannot be run directly and must be loaded into the browser.
mkdir testcp test.wasm testcp $GOROOT/misc/wasm/wasm_exec.{html,js} .
1.3.11 Test HTTP Server
Chrome does not support running Wasm in local files, so there must be an HTTP server
//http.gopackage mainimport ( "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) })))}
1.3.2 Http.go
1.4 Effects
Open http://localhost:8080/wasm_exec.html in the browser, click the Run button, you can see the Hello, webassembly! string in the console
2. Run Wasm in node
This is more straightforward.
node wasm_exec.js test.wasm
You can see the Hello, webassembly! string in the console.
3. Other examples
You can see more examples in example.
3.1 Bouncy
3.2 Ranbow-mouse
Will follow the mouse to draw a rainbow pattern, pretty good
3.3 Bumpy
Can draw some custom shape, the shape is different, the landing effect is different. The ball will bounce and the triangle will not. But it's not bad, not deformed, that's not true.
Get started with Go writing webassembly