-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathweb_embed.go
More file actions
74 lines (64 loc) · 1.53 KB
/
web_embed.go
File metadata and controls
74 lines (64 loc) · 1.53 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
package main
import (
"embed"
"io/fs"
"mime"
"net/http"
"path"
"regexp"
"strings"
)
//go:embed frontend/dist
var embeddedFrontend embed.FS
var frontendFS fs.FS
var hashedAssetPattern = regexp.MustCompile(`-[a-zA-Z0-9]{8,}\.`)
func init() {
var err error
frontendFS, err = fs.Sub(embeddedFrontend, "frontend/dist")
if err != nil {
panic(err)
}
}
func shouldServeFrontend(pathname string) bool {
if pathname == "/" {
return true
}
if strings.HasPrefix(pathname, "/assets/") {
return true
}
switch pathname {
case "/favicon.ico", "/vite.svg", "/manifest.webmanifest":
return true
default:
return false
}
}
func serveFrontend(w http.ResponseWriter, r *http.Request) bool {
if !shouldServeFrontend(r.URL.Path) {
return false
}
name := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
if r.URL.Path == "/" || name == "." {
name = "index.html"
}
content, err := fs.ReadFile(frontendFS, name)
if err != nil {
return false
}
if contentType := mime.TypeByExtension(path.Ext(name)); contentType != "" {
w.Header().Set("Content-Type", contentType)
}
setStaticCacheHeader(w, name)
_, _ = w.Write(content)
return true
}
func setStaticCacheHeader(w http.ResponseWriter, name string) {
switch {
case strings.HasPrefix(name, "assets/") && hashedAssetPattern.MatchString(name):
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
case name == "index.html":
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
default:
w.Header().Set("Cache-Control", "public, max-age=3600")
}
}