-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp_fallback.go
More file actions
252 lines (227 loc) · 5.76 KB
/
Copy pathhttp_fallback.go
File metadata and controls
252 lines (227 loc) · 5.76 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package main
import (
"bytes"
"fmt"
"io/fs"
"mime"
"net/http"
"path"
"strings"
"sync"
"time"
)
const (
staticCacheMaxBytes = 32 << 20 // 32MB total
staticCacheMaxFileBytes = 2 << 20 // 2MB per file
)
// fileServerWithFallback tries to serve embedded static files first,
// and falls back to the status server if the file doesn't exist.
type fileServerWithFallback struct {
staticFS fs.FS
fallback http.Handler
cacheMu sync.RWMutex
cache map[string]cachedStaticFile
cacheBytes int64
}
type cachedStaticFile struct {
payload []byte
size int64
modTime time.Time
contentType string
}
func newEmbeddedStaticFileServer(fallback http.Handler) (*fileServerWithFallback, error) {
assets, err := newUIAssetLoader()
if err != nil {
return nil, err
}
staticFS, err := assets.staticFiles()
if err != nil {
return nil, err
}
return newStaticFileServer(staticFS, fallback), nil
}
func newStaticFileServer(staticFS fs.FS, fallback http.Handler) *fileServerWithFallback {
return &fileServerWithFallback{
staticFS: staticFS,
fallback: fallback,
}
}
func (h *fileServerWithFallback) ServeCached(w http.ResponseWriter, r *http.Request, cleanPath string) bool {
if h == nil || cleanPath == "" {
return false
}
h.cacheMu.RLock()
entry, ok := h.cache[cleanPath]
h.cacheMu.RUnlock()
if !ok || len(entry.payload) == 0 {
return false
}
if entry.contentType != "" {
w.Header().Set("Content-Type", entry.contentType)
}
http.ServeContent(w, r, path.Base(cleanPath), entry.modTime, bytes.NewReader(entry.payload))
return true
}
func (h *fileServerWithFallback) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
h.serveFallback(w, r)
return
}
if h.ServePath(w, r, r.URL.Path) {
return
}
h.serveFallback(w, r)
}
func (h *fileServerWithFallback) ServePath(w http.ResponseWriter, r *http.Request, requestPath string) bool {
if h == nil || h.staticFS == nil {
return false
}
cleanPath, ok := cleanStaticAssetPath(requestPath)
if !ok {
return false
}
if h.ServeCached(w, r, cleanPath) {
return true
}
info, err := fs.Stat(h.staticFS, cleanPath)
if err != nil || info.IsDir() {
return false
}
payload, err := fs.ReadFile(h.staticFS, cleanPath)
if err != nil {
return false
}
if int64(len(payload)) != info.Size() {
return false
}
contentType := detectContentType(cleanPath, payload)
if canCacheStaticFile(info) {
h.reserveStaticCacheSpace(info.Size())
h.storeCached(cleanPath, info, payload, contentType)
}
w.Header().Set("Content-Type", contentType)
http.ServeContent(w, r, path.Base(cleanPath), info.ModTime(), bytes.NewReader(payload))
return true
}
func (h *fileServerWithFallback) storeCached(cleanPath string, info fs.FileInfo, payload []byte, contentType string) {
h.cacheMu.Lock()
defer h.cacheMu.Unlock()
if h.cache == nil {
h.cache = make(map[string]cachedStaticFile)
}
if prev, ok := h.cache[cleanPath]; ok {
h.cacheBytes -= prev.size
}
h.cacheBytes += info.Size()
h.cache[cleanPath] = cachedStaticFile{
payload: payload,
size: info.Size(),
modTime: info.ModTime(),
contentType: contentType,
}
}
func (h *fileServerWithFallback) reserveStaticCacheSpace(size int64) {
h.cacheMu.Lock()
defer h.cacheMu.Unlock()
if h.cache == nil {
h.cache = make(map[string]cachedStaticFile)
}
if h.cacheBytes+size > staticCacheMaxBytes {
h.cache = make(map[string]cachedStaticFile)
h.cacheBytes = 0
}
}
func (h *fileServerWithFallback) PreloadCache() error {
if h == nil {
return nil
}
if h.staticFS == nil {
return fmt.Errorf("static asset filesystem not configured")
}
h.cacheMu.Lock()
if h.cache == nil {
h.cache = make(map[string]cachedStaticFile)
}
h.cacheMu.Unlock()
err := fs.WalkDir(h.staticFS, ".", func(assetPath string, d fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if d.IsDir() {
if d.Name() == ".well-known" {
return fs.SkipDir
}
return nil
}
info, err := d.Info()
if err != nil {
return nil
}
if !canCacheStaticFile(info) {
return nil
}
cleanPath, ok := cleanStaticAssetPath(assetPath)
if !ok {
return nil
}
payload, err := fs.ReadFile(h.staticFS, cleanPath)
if err != nil {
return nil
}
if int64(len(payload)) != info.Size() {
return nil
}
h.reserveStaticCacheSpace(info.Size())
contentType := detectContentType(cleanPath, payload)
h.storeCached(cleanPath, info, payload, contentType)
return nil
})
if err != nil {
return err
}
return nil
}
func (h *fileServerWithFallback) ReloadCache() error {
if h == nil {
return nil
}
h.cacheMu.Lock()
h.cache = make(map[string]cachedStaticFile)
h.cacheBytes = 0
h.cacheMu.Unlock()
return h.PreloadCache()
}
func (h *fileServerWithFallback) serveFallback(w http.ResponseWriter, r *http.Request) {
if h != nil && h.fallback != nil {
h.fallback.ServeHTTP(w, r)
return
}
http.NotFound(w, r)
}
func canCacheStaticFile(info fs.FileInfo) bool {
return info != nil && info.Size() > 0 && info.Size() <= staticCacheMaxFileBytes && info.Size() <= staticCacheMaxBytes
}
func detectContentType(cleanPath string, payload []byte) string {
ext := strings.ToLower(path.Ext(cleanPath))
contentType := mime.TypeByExtension(ext)
if contentType == "" {
contentType = http.DetectContentType(payload)
}
if contentType == "" {
contentType = "application/octet-stream"
}
return contentType
}
func cleanStaticAssetPath(requestPath string) (string, bool) {
requestPath = strings.TrimPrefix(requestPath, "/")
for _, part := range strings.Split(requestPath, "/") {
if part == ".." {
return "", false
}
}
cleanPath := strings.TrimPrefix(path.Clean("/"+requestPath), "/")
if cleanPath == "" || cleanPath == "." || !fs.ValidPath(cleanPath) {
return "", false
}
return cleanPath, true
}