gorunwasm -- an HTTP Server Wrapper For Go
Demo
<!doctype html> <title>Go WASM Hello World</title> <body> <div> <label for="who">Who are you?</label> <input id="who" type="text" size="20"> </div> <div id="output">...</div> <script src="wasm_exec.js"></script> <script src="index.js" data-input="#who" data-output="#output"></script> </body>
// +build js package main import ( "fmt" "os" "syscall/js" ) var document = js.Global().Get("document") func main() { input := document.Call("querySelector", os.Getenv("input")) output := document.Call("querySelector", os.Getenv("output")) input.Call("addEventListener", "change", js.FuncOf(func(this js.Value, args []js.Value) interface{} { val := input.Get("value") output.Set("innerText", fmt.Sprintf("Hello %q", val)) return nil })) select {} }
Then just gorunwasm within the folder containing those two files:
$ go get github.com/jcorbin/gorunwasm
$ gorunwasm
2019/05/27 19:14:53 Serving http files from "/Users/joshua/gorunwasm/hello"
2019/05/27 19:14:53 listening on http://127.0.0.1:58241Open the browser, and type in the input:
But the real joy comes during development, let's break it:
diff --git a/main.go b/main.go index 58886f6..956b143 100644 --- a/hello/main.go +++ b/hello/main.go @@ -24,7 +24,7 @@ func main() { input.Call("addEventListener", "change", js.FuncOf(func(this js.Value, args []js.Value) interf val := input.Get("value") output.Set("innerText", fmt.Sprintf("Hello %q", val)) - return nil + // return nil FIXME oops })) select {}
See the syscall/js package and the golang WebAssembly
wiki for more.
HTML
You may write an index.html file within your main package, which will cause
gorunwasm to host an http.FileServer out of the main package directory,
rather than providing a static default index.html.
Any custom index.html:
- MUST include
<script src="wasm_exec.js"></script>-- hosted from$GOROOT/misc/wasm/wasm_exec.js, and is part of the upstream wasm runtime. - SHOULD include
<script src="index.js"></script>-- isgorunwasm's runtime harness, which can be further customized with data attributes:data-argsprovides JSON-encoded command line arguments, and causes the wasm program to be immediately ran after compilation.data-argv0provides an alternate program name to run the Go program as; the default is "PACKAGENAME.wasm".data-hrefprovides an alternate URL to thebuild.jsonconfig endpoint.- any other data attributes are passed as environment variables to the Go
program; access them the normal way with
os.Getenv("name")

