Discover books, shows, and movies at your level. Track your progress by filling your Shelf with what you find, and share with other language learners. *No dusting required.
shlf.space
1package server
2
3import (
4 "log"
5 "net/http"
6 "strings"
7
8 "shlf.space/static"
9)
10
11func (s *Server) HandleStatic() http.Handler {
12 var staticHandler http.Handler
13
14 if s.config.Core.Dev {
15 fileSystem := http.Dir("./static/files")
16 fileServer := http.FileServer(fileSystem)
17 staticHandler = NoCache(http.StripPrefix("/static/", fileServer))
18 } else {
19 fs, err := static.FS()
20 if err != nil {
21 log.Fatal("failed to create embedded static file system: ", err)
22 }
23
24 fileSystem := fs
25 fileServer := http.FileServer(fileSystem)
26 staticHandler = Cache(http.StripPrefix("/static/", fileServer))
27 }
28
29 return staticHandler
30}
31
32func Cache(h http.Handler) http.Handler {
33 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
34 path := strings.Split(r.URL.Path, "?")[0]
35
36 if strings.HasSuffix(path, ".js") {
37 w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
38 } else {
39 w.Header().Set("Cache-Control", "public, max-age=3600")
40 }
41
42 h.ServeHTTP(w, r)
43 })
44}
45
46func NoCache(h http.Handler) http.Handler {
47 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
48 w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
49 w.Header().Set("Pragma", "no-cache")
50 w.Header().Set("Expires", "0")
51 h.ServeHTTP(w, r)
52 })
53}