Skip to content

Instantly share code, notes, and snippets.

@mattn
Created June 15, 2018 08:52
Show Gist options
  • Save mattn/5d3235f83c2a7ee580a240d3c5cfc0ab to your computer and use it in GitHub Desktop.
Save mattn/5d3235f83c2a7ee580a240d3c5cfc0ab to your computer and use it in GitHub Desktop.
// +build ignore
package main
func add(a, b int) int {
return a + b
}
func main() {
}
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
addr := flag.String("addr", ":5555", "server address:port")
flag.Parse()
http.HandleFunc("/", rootHandle)
http.HandleFunc("/wasm", wasmHandle)
log.Printf("listening on %q...", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
}
func rootHandle(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, page)
}
func wasmHandle(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/wasm")
f, err := os.Open("js")
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
io.Copy(w, f)
}
const page = `
<html>
<head>
<title>Testing WebAssembly</title>
<script type="text/javascript">
function fetchAndInstantiate(url, obj) {
return fetch(url).then(resp =>
resp.arrayBuffer()
).then(buf =>
WebAssembly.instantiate(buf, obj)
).then(results =>
results.instance
);
}
var mod = fetchAndInstantiate("/wasm", {});
window.onload = function() {
mod.then(function(instance) {
var div = document.getElementById("wasm-result");
div.innerHTML = "<code>add(1, 2)= " + instance.exports.add(1, 2) + "</code>";
});
};
</script>
</head>
<body>
<div id="wasm-result"><code>add(1, 2)= N/A</code></div>
</body>
</html>
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment