Created
June 15, 2018 08:52
-
-
Save mattn/67aa6e4def40addd230ff3ee7d251a76 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// +build ignore | |
package main | |
func add(a, b int) int { | |
return a + b | |
} | |
func main() { | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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