Go WebAssembly
scarcoco opened this issue · comments
https://github.com/golang/go/wiki/WebAssembly
hello world
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
to exec wasm, you need a javascript support file & html, copy it
cp "$(go env GOROOT)/misc/wasm/wasm_exec.js" .
html code
<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>
install & start a server listen on 8080
go get -u github.com/shurcooL/goexec
goexec 'http.ListenAndServe(`:8080`, http.FileServer(http.Dir(`.`)))'
open http://localhost:8080/index.html
exec wasm with node
By default, go_js_wasm_exec is in the misc/wasm directory of your Go installation
GOOS=js GOARCH=wasm go run -exec="$(go env GOROOT)/misc/wasm/go_js_wasm_exec" .
run go test
GOOS=js GOARCH=wasm go test -exec="$(go env GOROOT)/misc/wasm/go_js_wasm_exec"
add to path
export PATH="$PATH:$(go env GOROOT)/misc/wasm"
GOOS=js GOARCH=wasm go run .
GOOS=js GOARCH=wasm go test
run test in browser
You can also use wasmbrowsertest to run tests inside your browser
GOOS=js GOARCH=wasm go test -exec="$GOPATH/bin/wasmbrowsertest"