Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created September 3, 2018 07:21
Show Gist options
  • Save miguelmota/67d212e8905ae009753e48012476af65 to your computer and use it in GitHub Desktop.
Save miguelmota/67d212e8905ae009753e48012476af65 to your computer and use it in GitHub Desktop.
Go (golang) WebAssembly (WASM) hello world example
package main
import (
"syscall/js"
)
// Add ...
func Add(a, b int) int {
return a + b
}
func main() {
c := make(chan struct{}, 0)
add := func(args []js.Value) {
go func() {
js.Global().Set("output", js.ValueOf(Add(args[0].Int(), args[1].Int())))
close(c)
}()
}
js.Global().Set("add", js.NewCallback(add))
<-c
}
compile:
GOARCH=wasm GOOS=js go build -o test.wasm main.go
copy:
cp $(go env GOROOT)/misc/wasm/wasm_exec.{html,js} .
serve:
go run server.go
package main
import (
"flag"
"log"
"net/http"
"strings"
)
var (
listen = flag.String("listen", ":8080", "listen address")
dir = flag.String("dir", ".", "directory to serve")
)
func main() {
flag.Parse()
log.Printf("listening on %q...", *listen)
log.Fatal(http.ListenAndServe(*listen, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if strings.HasSuffix(req.URL.Path, ".wasm") {
resp.Header().Set("content-type", "application/wasm")
}
http.FileServer(http.Dir(*dir)).ServeHTTP(resp, req)
})))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment