package routes import ( "git.soup.land/soup/shelves" "git.soup.land/soup/shelves/internal/httpx" "html/template" "net/http" "strings" "time" ) func html(w http.ResponseWriter, s template.HTML) { w.Header().Add("Content-Type", "text/html") w.Write([]byte(s)) } func redirectSetup(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := httpx.GetCtx(r) if ctx.NeedsOwnerSetup && !strings.HasPrefix(r.URL.Path, "/static") { if r.URL.Path != "/setup" { httpx.SeeOther(w, "/setup") return } } next.ServeHTTP(w, r) }) } func ServeStatic() http.Handler { inner := http.StripPrefix("/static/", http.FileServerFS(shelves.Frontend)) startup := time.Now().UTC() return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ims := r.Header.Get("If-Modified-Since") imsTime, _ := time.Parse(http.TimeFormat, ims) imsTime = imsTime.Add(time.Second * 10) if imsTime.Before(startup) { w.Header().Add("Last-Modified", startup.Format(http.TimeFormat)) w.Header().Add("Cache-Control", "public, max-age=0, stale-while-revalidate=9999999") inner.ServeHTTP(w, r) } else { w.WriteHeader(http.StatusNotModified) } }) } func Routes() http.Handler { mux := http.NewServeMux() mux.Handle("GET /static/", ServeStatic()) mux.HandleFunc("GET /{$}", HomeGet) mux.HandleFunc("GET /settings", SettingsGet) mux.HandleFunc("POST /settings", SettingsPost) mux.HandleFunc("GET /login", LoginGet) mux.HandleFunc("POST /login", LoginPost) mux.HandleFunc("DELETE /login", LoginDelete) return redirectSetup(mux) }