Skip to content

Instantly share code, notes, and snippets.

@metalmatze
Created June 29, 2018 22:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metalmatze/e986227a70a36a79b73130228cd58f42 to your computer and use it in GitHub Desktop.
Save metalmatze/e986227a70a36a79b73130228cd58f42 to your computer and use it in GitHub Desktop.
Run Go as WebAssembly
package main
import (
"fmt"
"net/http"
)
// https://github.com/golang/go/tree/master/misc/wasm
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/wasm_exec.js", jsHandler)
http.HandleFunc("/test.wasm", wasmHandler)
fmt.Println("running http server")
http.ListenAndServe(":8000", nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "wasm_exec.html")
}
func jsHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "wasm_exec.js")
}
func wasmHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/wasm")
http.ServeFile(w, r, "wasm")
}
package main
import (
"log"
"syscall/js"
)
// GOARCH=wasm GOOS=js go1.11beta1 build -ldflags '-w' ./cmd/wasm
func main() {
var cb js.Callback
cb = js.NewCallback(func(args []js.Value) {
log.Println("button clicked")
// cb.Release() // release the callback if the button will not be clicked again
})
js.Global().Get("document").Call("getElementById", "myButton").Call("addEventListener", "click", cb)
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment