Skip to content

Commit b7bed6b

Browse files
feat: Cache-Control for web.FS
1 parent 2c041ac commit b7bed6b

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

web/http/router.go

+36-2
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ package http
22

33
import (
44
"io/fs"
5+
"net/http"
56

67
"github.com/ItsNotGoodName/smtpbridge/internal/core"
7-
"github.com/ItsNotGoodName/smtpbridge/pkg/chiext"
88
"github.com/ItsNotGoodName/smtpbridge/web"
99
"github.com/ItsNotGoodName/smtpbridge/web/pages"
1010
"github.com/ItsNotGoodName/smtpbridge/web/routes"
@@ -25,7 +25,7 @@ func NewRouter(ct pages.Controller, app core.App, fileFS fs.FS, csrfSecret []byt
2525
r.Use(middleware.Recoverer)
2626
r.Use(csrf.Protect(csrfSecret, csrf.Secure(false)))
2727

28-
chiext.MountFS(r, web.FS)
28+
mountWebFS(r, web.FS)
2929

3030
// Login
3131
r.Group(func(r chi.Router) {
@@ -125,3 +125,37 @@ func NewRouter(ct pages.Controller, app core.App, fileFS fs.FS, csrfSecret []byt
125125

126126
return r
127127
}
128+
129+
func mountWebFS(r chi.Router, f fs.FS) error {
130+
fsHandler := http.StripPrefix("/", http.FileServer(http.FS(f)))
131+
132+
normalFS := func(w http.ResponseWriter, r *http.Request) {
133+
w.Header().Set("Cache-Control", "max-age=3600")
134+
fsHandler.ServeHTTP(w, r)
135+
}
136+
137+
// Files in assets have a hash
138+
assetsFS := func(w http.ResponseWriter, r *http.Request) {
139+
w.Header().Set("Cache-Control", "max-age=31536000,immutable")
140+
fsHandler.ServeHTTP(w, r)
141+
}
142+
143+
if files, err := fs.ReadDir(f, "."); err == nil {
144+
for _, f := range files {
145+
name := f.Name()
146+
if f.IsDir() {
147+
if name == "assets" {
148+
r.Get("/"+name+"/*", assetsFS)
149+
} else {
150+
r.Get("/"+name+"/*", normalFS)
151+
}
152+
} else {
153+
r.Get("/"+name, normalFS)
154+
}
155+
}
156+
} else if err != fs.ErrNotExist {
157+
return err
158+
}
159+
160+
return nil
161+
}

0 commit comments

Comments
 (0)