Skip to content

Instantly share code, notes, and snippets.

@antoineMoPa
Forked from miguelmota/Makefile
Last active October 22, 2022 16:07
Show Gist options
  • Save antoineMoPa/fca409332ff605f1333ed4fb54c4d9a2 to your computer and use it in GitHub Desktop.
Save antoineMoPa/fca409332ff605f1333ed4fb54c4d9a2 to your computer and use it in GitHub Desktop.
Go (golang) WebAssembly (WASM) hello world example

Readme

First, get all files from this gist in a local folder.

Then, copy required html and js files from your go installation:

cp $(go env GOROOT)/misc/wasm/wasm_exec.{html,js} .

Then, run your project:

make

That's it, you are a go-wasm specialist now 😎

package main
import (
"syscall/js"
)
func main() {
c := make(chan bool, 0)
add := func (this js.Value, inputs []js.Value) interface{} {
return js.ValueOf(inputs[0].Int() + inputs[1].Int())
}
closeGo := func(this js.Value, inputs []js.Value) interface {} {
c <- true
return nil
}
setGlobal42 := func (this js.Value, inputs []js.Value) interface {} {
js.Global().Set("$42", js.ValueOf(42))
return nil
}
js.Global().Set("add", js.FuncOf(add))
js.Global().Set("closeGo", js.FuncOf(closeGo))
js.Global().Set("setGlobal42", js.FuncOf(setGlobal42))
<-c
}
serve: compile
go run server.go
compile: main.go
GOARCH=wasm GOOS=js go build -o test.wasm main.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