-
Notifications
You must be signed in to change notification settings - Fork 22
/
handler.go
148 lines (136 loc) · 3.35 KB
/
handler.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
package main
import (
"crypto/rand"
_ "embed"
"encoding/base64"
"errors"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"github.com/agnivade/wasmbrowsertest/filesys"
)
//go:embed index.html
var indexHTML string
type wasmServer struct {
indexTmpl *template.Template
wasmFile string
wasmExecJS []byte
args []string
envMap map[string]string
logger *log.Logger
fsHandler *filesys.Handler
securityToken string
}
var wasmLocations = []string{
"misc/wasm/wasm_exec.js",
"lib/wasm/wasm_exec.js",
}
func NewWASMServer(wasmFile string, args []string, coverageFile string, l *log.Logger) (http.Handler, error) {
var err error
srv := &wasmServer{
wasmFile: wasmFile,
args: args,
logger: l,
envMap: make(map[string]string),
}
// try for some security on an api capable of
// reads and writes to the file system
srv.securityToken, err = generateToken()
if err != nil {
return nil, err
}
srv.fsHandler = filesys.NewHandler(srv.securityToken, l)
for _, env := range os.Environ() {
vars := strings.SplitN(env, "=", 2)
srv.envMap[vars[0]] = vars[1]
}
var buf []byte
for _, loc := range wasmLocations {
buf, err = os.ReadFile(filepath.Join(runtime.GOROOT(), loc))
if err == nil {
break
}
if !os.IsNotExist(err) {
return nil, err
}
}
if err != nil {
var perr *os.PathError
if errors.As(err, &perr) {
if strings.Contains(perr.Path, filepath.Join("golang.org", "toolchain")) {
return nil, fmt.Errorf("The Go toolchain does not include the WebAssembly exec helper before Go 1.24. Please copy wasm_exec.js to %s", filepath.Join(runtime.GOROOT(), "misc", "wasm", "wasm_exec.js"))
}
}
return nil, err
}
srv.wasmExecJS = buf
srv.indexTmpl, err = template.New("index").Parse(indexHTML)
if err != nil {
return nil, err
}
return srv, nil
}
func (ws *wasmServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// log.Println(r.URL.Path)
switch r.URL.Path {
case "/", "/index.html":
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
data := struct {
WASMFile string
Args []string
EnvMap map[string]string
SecurityToken string
Pid int
Ppid int
}{
WASMFile: filepath.Base(ws.wasmFile),
Args: ws.args,
EnvMap: ws.envMap,
SecurityToken: ws.securityToken,
Pid: os.Getpid(),
Ppid: os.Getppid(),
}
err := ws.indexTmpl.Execute(w, data)
if err != nil {
ws.logger.Println(err)
}
case "/" + filepath.Base(ws.wasmFile):
f, err := os.Open(ws.wasmFile)
if err != nil {
ws.logger.Println(err)
return
}
defer func() {
err := f.Close()
if err != nil {
ws.logger.Println(err)
}
}()
http.ServeContent(w, r, r.URL.Path, time.Now(), f)
case "/wasm_exec.js":
w.Header().Set("Content-Type", "application/javascript")
w.Header().Set("Content-Length", strconv.Itoa(len(ws.wasmExecJS)))
if _, err := w.Write(ws.wasmExecJS); err != nil {
ws.logger.Println("unable to write wasm_exec.")
}
default:
if strings.HasPrefix(r.URL.Path, "/fs/") {
ws.fsHandler.ServeHTTP(w, r)
}
}
}
func generateToken() (string, error) {
buf := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, buf); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(buf), nil
}