-
Notifications
You must be signed in to change notification settings - Fork 5
/
run-demo.go
66 lines (56 loc) · 1.25 KB
/
run-demo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// +build ignore
package main
import (
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
)
var pt = fmt.Printf
func main() {
srcFile := "demo.go"
if len(os.Args) > 1 {
srcFile = filepath.Clean(os.Args[1])
}
wasmFile := srcFile[:strings.LastIndex(srcFile, ".go")] + ".wasm"
pt("src %s, wasm %s\n", srcFile, wasmFile)
cmd := exec.Command("go", "build", "-o", wasmFile, srcFile)
cmd.Env = append(os.Environ(),
"GOOS=js",
"GOARCH=wasm",
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
dirFS := os.DirFS(".")
http.Handle("/", http.FileServer(http.FS(dirFS)))
http.HandleFunc("/demo.html", func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="wasm_exec.js"></script>
</head>
<body>
<div id="app"></div>
<script>
(async function exec() {
const go = new Go();
const result = await WebAssembly.instantiateStreaming(
fetch("` + wasmFile + `"), go.importObject);
await go.run(result.instance);
})()
</script>
</body>
</html>
`))
})
addr := "127.0.0.1:46789"
fmt.Printf("http://%s/demo.html\n", addr)
http.ListenAndServe(addr, nil)
}