src/examples/wasm: Show both methods supported

Adds another example showing the simple case
of executing main, adds a README explaining how
everything fits together and how to execute the compiled
code in the browser. Include a minimal webserver for
local testing.
This commit is contained in:
Johan Brandhorst
2019-04-16 14:58:11 +01:00
committed by Ron Evans
parent a00a51e70e
commit 586023b45d
12 changed files with 244 additions and 25 deletions
+20
View File
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Go WebAssembly</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="wasm_exec.js" defer></script>
<script src="wasm.js" defer></script>
</head>
<body>
<h1>WebAssembly</h1>
<p>Add two numbers, using WebAssembly:</p>
<input type="number" id="a" value="2" /> + <input type="number" id="b" value="2" /> = <input type="number"
id="result" readonly />
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
package main
import (
"strconv"
"syscall/js"
)
func main() {
}
//go:export add
func add(a, b int) int {
return a + b
}
//go:export update
func update() {
document := js.Global().Get("document")
aStr := document.Call("getElementById", "a").Get("value").String()
bStr := document.Call("getElementById", "b").Get("value").String()
a, _ := strconv.Atoi(aStr)
b, _ := strconv.Atoi(bStr)
result := add(a, b)
document.Call("getElementById", "result").Set("value", result)
}
+35
View File
@@ -0,0 +1,35 @@
'use strict';
const WASM_URL = 'wasm.wasm';
var wasm;
function updateResult() {
wasm.exports.update();
}
function init() {
document.querySelector('#a').oninput = updateResult;
document.querySelector('#b').oninput = updateResult;
const go = new Go();
if ('instantiateStreaming' in WebAssembly) {
WebAssembly.instantiateStreaming(fetch(WASM_URL), go.importObject).then(function (obj) {
wasm = obj.instance;
go.run(wasm);
updateResult();
})
} else {
fetch(WASM_URL).then(resp =>
resp.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, go.importObject).then(function (obj) {
wasm = obj.instance;
go.run(wasm);
updateResult();
})
)
}
}
init();