-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
202 lines (183 loc) · 5.38 KB
/
main.go
File metadata and controls
202 lines (183 loc) · 5.38 KB
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"embed"
"flag"
"fmt"
"io/fs"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"github.com/evanw/esbuild/pkg/api"
)
//go:generate go run . -build
//go:embed ui/www
var embedded embed.FS
func main() {
dev := flag.Bool("dev", false, "run in development mode with esbuild watch and live reload")
build := flag.Bool("build", false, "run a production esbuild build and exit")
addr := flag.String("addr", "localhost:8080", "listen address")
flag.Parse()
if *build {
buildProd()
return
}
mux := http.NewServeMux()
if *dev {
mux.Handle("/", devHandler())
} else {
mux.Handle("/", prodHandler())
}
log.Printf("listening on %s", *addr)
handler := withCSP(mux)
handler = lineHackHandler(handler)
if err := http.ListenAndServe(*addr, handler); err != nil {
log.Fatal(err)
}
}
// withCSP wraps a handler to set a Content-Security-Policy header on all responses.
func withCSP(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy",
"default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'unsafe-inline'; font-src 'self'; img-src 'self'; worker-src blob:; connect-src 'self' https://proxy.golang.org")
h.ServeHTTP(w, r)
})
}
// lineHackHandler is a hack that redirects URLs like
//
// https://pkg.geomys.dev/golang.org/x/crypto@v0.48.0/ssh/client_auth.go;l=524
// https://pkg.geomys.dev/crypto/tls@go1.26.0/tls.go;l=59
//
// generated by a buggy early version of the extension to the correct URL with a
// line number fragment.
func lineHackHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
firstSegment, _, _ := strings.Cut(r.URL.Path, "/")
firstSegment, _, _ = strings.Cut(firstSegment, "@")
if strings.Contains(firstSegment, ".") && firstSegment != "golang.org" {
next.ServeHTTP(w, r)
return
}
if !strings.Contains(r.URL.Path, ";l=") {
next.ServeHTTP(w, r)
return
}
u := *r.URL
u.Path, u.Fragment, _ = strings.Cut(u.Path, ";l=")
u.Fragment = "L" + u.Fragment
http.Redirect(w, r, u.String(), http.StatusFound)
})
}
// esbuildOptions returns the shared esbuild build options.
func esbuildOptions() api.BuildOptions {
return api.BuildOptions{
EntryPoints: []string{"ui/src/index.ts"},
Bundle: true,
Format: api.FormatESModule,
Outdir: "ui/www",
Sourcemap: api.SourceMapLinked,
TreeShaking: api.TreeShakingTrue,
}
}
// buildProd runs a one-shot production build with minification.
func buildProd() {
opts := esbuildOptions()
opts.LogLevel = api.LogLevelInfo
opts.MinifySyntax = true
opts.MinifyWhitespace = true
opts.MinifyIdentifiers = true
opts.Write = true
opts.Define = map[string]string{"process.env.NODE_ENV": `"production"`}
result := api.Build(opts)
if len(result.Errors) > 0 {
os.Exit(1)
}
}
// devHandler starts esbuild in serve+watch mode and proxies the build
// output and SSE endpoint to it. Static files are served from disk,
// and all other paths get index.html (SPA routing).
func devHandler() http.Handler {
opts := esbuildOptions()
opts.Define = map[string]string{"process.env.NODE_ENV": `"development"`}
ctx, ctxErr := api.Context(opts)
if ctxErr != nil {
fmt.Fprintf(os.Stderr, "esbuild context error: %v\n", ctxErr)
os.Exit(1)
}
if err := ctx.Watch(api.WatchOptions{}); err != nil {
fmt.Fprintf(os.Stderr, "esbuild watch error: %v\n", err)
os.Exit(1)
}
result, err := ctx.Serve(api.ServeOptions{})
if err != nil {
fmt.Fprintf(os.Stderr, "esbuild serve error: %v\n", err)
os.Exit(1)
}
host := "127.0.0.1"
if len(result.Hosts) > 0 {
host = result.Hosts[0]
}
esbuildURL, _ := url.Parse(fmt.Sprintf("http://%s:%d", host, result.Port))
proxy := httputil.NewSingleHostReverseProxy(esbuildURL)
www := os.DirFS("ui/www")
fileServer := http.FileServer(http.FS(www))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Proxy esbuild build output and live reload endpoint.
if r.URL.Path == "/esbuild" || strings.HasPrefix(r.URL.Path, "/index.js") {
proxy.ServeHTTP(w, r)
return
}
// Serve static files from disk (fonts, zip, etc.).
p := strings.TrimPrefix(r.URL.Path, "/")
if p != "" {
if _, err := fs.Stat(www, p); err == nil {
fileServer.ServeHTTP(w, r)
return
}
}
// Home page.
if r.URL.Path == "/" {
http.ServeFile(w, r, "ui/www/home.html")
return
}
// SPA fallback.
http.ServeFile(w, r, "ui/www/index.html")
})
}
// prodHandler serves embedded static files with SPA fallback to index.html.
func prodHandler() http.Handler {
www, err := fs.Sub(embedded, "ui/www")
if err != nil {
log.Fatal(err)
}
fileServer := http.FileServer(http.FS(www))
indexHTML, err := fs.ReadFile(www, "index.html")
if err != nil {
log.Fatal(err)
}
homeHTML, err := fs.ReadFile(www, "home.html")
if err != nil {
log.Fatal(err)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Try to serve a static file. If it doesn't exist, serve index.html.
p := strings.TrimPrefix(r.URL.Path, "/")
if p != "" {
if _, err := fs.Stat(www, p); err == nil {
fileServer.ServeHTTP(w, r)
return
}
}
// Home page.
if r.URL.Path == "/" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(homeHTML)
return
}
// SPA fallback.
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(indexHTML)
})
}