package server import ( "log" "net/http" "strings" "shlf.space/static" ) func (s *Server) HandleStatic() http.Handler { var staticHandler http.Handler if s.config.Core.Dev { fileSystem := http.Dir("./static/files") fileServer := http.FileServer(fileSystem) staticHandler = NoCache(http.StripPrefix("/static/", fileServer)) } else { fs, err := static.FS() if err != nil { log.Fatal("failed to create embedded static file system: ", err) } fileSystem := fs fileServer := http.FileServer(fileSystem) staticHandler = Cache(http.StripPrefix("/static/", fileServer)) } return staticHandler } func Cache(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := strings.Split(r.URL.Path, "?")[0] if strings.HasSuffix(path, ".js") { w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") } else { w.Header().Set("Cache-Control", "public, max-age=3600") } h.ServeHTTP(w, r) }) } func NoCache(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Header().Set("Pragma", "no-cache") w.Header().Set("Expires", "0") h.ServeHTTP(w, r) }) }