/
handler.go
94 lines (81 loc) · 2.29 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
package web
import (
"bytes"
"crypto/sha256"
"embed"
"encoding/hex"
"fmt"
"github.com/target/goalert/config"
"github.com/target/goalert/util/errutil"
"io/fs"
"net/http"
"net/http/httputil"
"net/url"
"path"
"sync"
"time"
"github.com/pkg/errors"
)
//go:embed src/build
var bundleFS embed.FS
// NewHandler creates a new http.Handler that will serve UI files
// using bundled assets or by proxying to urlStr if set.
func NewHandler(urlStr, prefix string) (http.Handler, error) {
mux := http.NewServeMux()
etags := make(map[string]string)
var mx sync.Mutex
calcTag := func(name string, data []byte) string {
mx.Lock()
defer mx.Unlock()
tag, ok := etags[name]
if ok {
return tag
}
sum := sha256.Sum256(data)
tag = `W/"` + hex.EncodeToString(sum[:]) + `"`
etags[name] = tag
return tag
}
var extraScripts []string
if urlStr == "" {
mux.HandleFunc("/static/", func(w http.ResponseWriter, req *http.Request) {
data, err := bundleFS.ReadFile(path.Join("src/build", req.URL.Path))
if errors.Is(err, fs.ErrNotExist) {
http.NotFound(w, req)
return
}
w.Header().Set("Cache-Control", "public; max-age=60, stale-while-revalidate=600, stale-if-error=259200")
w.Header().Set("ETag", calcTag(req.URL.Path, data))
http.ServeContent(w, req, req.URL.Path, time.Time{}, bytes.NewReader(data))
})
} else {
u, err := url.Parse(urlStr)
if err != nil {
return nil, errors.Wrap(err, "parse url")
}
proxy := httputil.NewSingleHostReverseProxy(u)
mux.Handle("/static/", proxy)
mux.Handle("/build/", proxy)
// dev mode
extraScripts = []string{"vendor.js"}
}
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
cfg := config.FromContext(req.Context())
var buf bytes.Buffer
err := indexTmpl.Execute(&buf, renderData{
ApplicationName: cfg.ApplicationName(),
Prefix: prefix,
ExtraScripts: extraScripts,
})
if errutil.HTTPError(req.Context(), w, err) {
return
}
h := sha256.New()
h.Write(buf.Bytes())
indexETag := fmt.Sprintf(`"sha256-%s"`, hex.EncodeToString(h.Sum(nil)))
w.Header().Set("Cache-Control", "private; max-age=60, stale-while-revalidate=600, stale-if-error=259200")
w.Header().Set("ETag", indexETag)
http.ServeContent(w, req, "/", time.Time{}, bytes.NewReader(buf.Bytes()))
})
return mux, nil
}