static.go (1100B)
1 package server 2 3 import ( 4 "fmt" 5 "lyrics/static" 6 "net/http" 7 ) 8 9 func Static(dev bool) (http.Handler, error) { 10 var finalHandler http.Handler 11 12 if dev { 13 fileSystem := http.Dir("static/files") 14 fileServer := http.FileServer(fileSystem) 15 finalHandler = NoCache(http.StripPrefix("/static/", fileServer)) 16 } else { 17 fs, err := static.FS() 18 if err != nil { 19 return finalHandler, fmt.Errorf("failed to create embedded static file system: %w", err) 20 } 21 fileSystem := fs 22 fileServer := http.FileServer(fileSystem) 23 finalHandler = Cache(http.StripPrefix("/static/", fileServer)) 24 } 25 26 return finalHandler, nil 27 } 28 29 func Cache(h http.Handler) http.Handler { 30 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 31 w.Header().Set("Cache-Control", "public, max-age=3600") 32 h.ServeHTTP(w, r) 33 }) 34 } 35 36 func NoCache(h http.Handler) http.Handler { 37 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 38 w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") 39 w.Header().Set("Pragma", "no-cache") 40 w.Header().Set("Expires", "0") 41 h.ServeHTTP(w, r) 42 }) 43 }