Files
lingniu-vehicle-ingest/vehicle-data-platform/apps/api/internal/static/static.go
T

40 lines
997 B
Go

package static
import (
"net/http"
"os"
"path/filepath"
"strings"
)
func Handler(dir string, fallback http.Handler) http.Handler {
if strings.TrimSpace(dir) == "" {
return fallback
}
fs := http.FileServer(http.Dir(dir))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
fallback.ServeHTTP(w, r)
return
}
path := filepath.Join(dir, filepath.Clean(r.URL.Path))
if info, err := os.Stat(path); err == nil && !info.IsDir() {
setCachePolicy(w, r.URL.Path)
fs.ServeHTTP(w, r)
return
}
w.Header().Set("Cache-Control", "no-store")
http.ServeFile(w, r, filepath.Join(dir, "index.html"))
})
}
func setCachePolicy(w http.ResponseWriter, path string) {
if path == "/" || path == "/index.html" || path == "/app-config.js" {
w.Header().Set("Cache-Control", "no-store")
return
}
if strings.HasPrefix(path, "/assets/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
}
}