/
main.go
166 lines (154 loc) · 4.31 KB
/
main.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
// wasmserve compiles a Go command to WebAssembly and serves it via HTTP.
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"github.com/shurcooL/go/osutil"
"github.com/shurcooL/home/httputil"
"github.com/shurcooL/httpgzip"
"github.com/shurcooL/users"
)
var httpFlag = flag.String("http", ":8080", "Listen for HTTP connections on this address.")
func main() {
flag.Parse()
err := run()
if err != nil {
log.Fatalln(err)
}
}
func run() error {
goroot, err := goroot()
if err != nil {
return err
}
err = http.ListenAndServe(*httpFlag, httputil.ErrorHandler(admin{}, handler{goroot}.ServeHTTP))
return err
}
type handler struct {
goroot string
}
func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) error {
if err := httputil.AllowMethods(req, http.MethodGet, http.MethodHead); err != nil {
return err
}
switch {
case req.URL.Path == "/main.wasm":
tempDir, err := ioutil.TempDir("", "")
if err != nil {
return err
}
defer os.RemoveAll(tempDir)
wasmFile := filepath.Join(tempDir, "main.wasm")
cmd := exec.CommandContext(req.Context(), "go", "build", "-tags=nethttpomithttp2", "-o", wasmFile)
env := osutil.Environ(os.Environ())
env.Set("GOOS", "js")
env.Set("GOARCH", "wasm")
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%q: %v\n\n%s", cmd.Args, err, out)
}
w.Header().Set("Content-Type", "application/wasm")
return serveFile(w, req, wasmFile)
case req.URL.Path == "/wasm_exec.js":
w.Header().Set("Content-Type", "application/javascript")
return serveFile(w, req, filepath.Join(h.goroot, "misc", "wasm", "wasm_exec.js"))
case req.URL.Path == "/favicon.ico":
return os.ErrNotExist
default:
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if req.Method == http.MethodHead {
return nil
}
_, err := io.WriteString(w, `<!DOCTYPE html>
<html lang="en">
<head>
<script src="/wasm_exec.js"></script>
<script>
if (!WebAssembly.instantiateStreaming) { // polyfill for Safari :/
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
const resp = fetch("/main.wasm").then((resp) => {
if (!resp.ok) {
resp.text().then((body) => {
document.body.innerHTML = "<pre>" + body + "</pre>";
});
throw new Error("did not get acceptable status code: " + resp.status);
}
return resp;
});
WebAssembly.instantiateStreaming(resp, go.importObject).then((result) => {
go.run(result.instance);
}).catch((error) => { document.body.textContent = error; });
window.addEventListener('keydown', (event) => {
if (event.key !== '®') {
return;
}
event.preventDefault();
document.body.innerHTML = "";
const resp = fetch("/main.wasm").then((resp) => {
if (!resp.ok) {
resp.text().then((body) => {
document.body.innerHTML = "<pre>" + body + "</pre>";
});
throw new Error("did not get acceptable status code: " + resp.status);
}
return resp;
});
WebAssembly.instantiateStreaming(resp, go.importObject).then((result) => {
go.run(result.instance);
}).catch((error) => { document.body.textContent = error; });
});
</script>
</head>
<body></body>
</html>`)
return err
}
}
func serveFile(w http.ResponseWriter, req *http.Request, path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
httpgzip.ServeContent(w, req, fi.Name(), fi.ModTime(), f)
return nil
}
type admin struct{}
func (admin) GetAuthenticated(context.Context) (users.User, error) {
return users.User{SiteAdmin: true}, nil
}
// goroot returns the go env GOROOT value by invoking the go command.
func goroot() (string, error) {
out, err := exec.Command("go", "env", "-json", "GOROOT").Output()
if ee := (*exec.ExitError)(nil); errors.As(err, &ee) {
return "", fmt.Errorf("go command exited unsuccessfully: %v\n%s", ee.ProcessState.String(), ee.Stderr)
} else if err != nil {
return "", err
}
var env struct{ GOROOT string }
err = json.Unmarshal(out, &env)
if err != nil {
return "", err
}
return env.GOROOT, nil
}