Skip to content

Instantly share code, notes, and snippets.

@deezone
Last active May 19, 2020 11:00
Show Gist options
  • Save deezone/27047653857283719cd3a41f08a7f803 to your computer and use it in GitHub Desktop.
Save deezone/27047653857283719cd3a41f08a7f803 to your computer and use it in GitHub Desktop.
Wasm - Hello World via console
<!-- /out/index.html -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Go Wasm</title>
</head>
<body>
<script src="wasm_exec.js"></script>
<script>
if (WebAssembly) {
// WebAssembly.instantiateStreaming is not currently available in Safari
if (WebAssembly && !WebAssembly.instantiateStreaming) { // polyfill
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((res) => {
go.run(res.instance);
});
} else {
console.log("WebAssembly is not supported in your browser")
}
</script>
</body>
</html>
// +build js,wasm
// /go/main.go
// GOOS=js GOARCH=wasm go build -o out/main.wasm go/main.go
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello WASM from Go!")
}
// webServer.go
package main
import (
"log"
"net/http"
"strings"
)
const dir = "./out"
// create a handler struct
type HttpHandler struct{}
// implement `ServeHTTP` method on `HttpHandler` struct
func (h HttpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
fs := http.FileServer(http.Dir(dir))
log.Print("Serving " + dir + " on http://localhost:8080")
res.Header().Add("Cache-Control", "no-cache")
if strings.HasSuffix(req.URL.Path, ".wasm") {
res.Header().Set("content-type", "application/wasm")
}
fs.ServeHTTP(res, req)
}
func main() {
// create a new handler
handler := HttpHandler{}
// listen and serve
http.ListenAndServe(":8080", handler)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment