Last active
May 19, 2020 11:00
-
-
Save deezone/27047653857283719cd3a41f08a7f803 to your computer and use it in GitHub Desktop.
Wasm - Hello World via console
This file contains 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
<!-- /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> |
This file contains 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 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!") | |
} |
This file contains 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
// 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