package web import ( "errors" "io/fs" "net/http" "github.com/google/uuid" "github.com/gramanas/blogspace/internal/store" ) // handleMedia serves an uploaded file. Ids are immutable, so clients may cache // forever (a renamed file keeps its old download name in caches; acceptable). // What may render inline is decided by servedAs, see filetype.go. func (s *Server) handleMedia(w http.ResponseWriter, r *http.Request) { id, err := uuid.Parse(r.PathValue("id")) if err != nil { http.NotFound(w, r) return } etag := `"` + id.String() + `"` if r.Header.Get("If-None-Match") == etag { w.WriteHeader(http.StatusNotModified) return } f, err := blogStore(r).FileMeta(r.Context(), id) if err != nil { if errors.Is(err, store.ErrNotFound) { http.NotFound(w, r) return } s.serverError(w, err) return } ctype, disposition := servedAs(f.ContentType, r.URL.Query().Has("download")) w.Header().Set("Content-Type", ctype) w.Header().Set("Content-Disposition", contentDisposition(disposition, f.Filename)) w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") w.Header().Set("ETag", etag) w.Header().Set("X-Content-Type-Options", "nosniff") http.ServeContent(w, r, f.Filename, f.CreatedAt, blogStore(r).FileReader(r.Context(), f)) } // handleFavicon answers the browsers that ask for /favicon.ico regardless of // the tags: the blog's own icon if it set one, else the // Blogspace default. Without this the request would render the 404 page. func (s *Server) handleFavicon(w http.ResponseWriter, r *http.Request) { if icon := ParseTheme(currentBlog(r).ThemeJSON).Favicon; icon != "" { http.Redirect(w, r, "/media/"+icon, http.StatusFound) return } data, err := fs.ReadFile(s.tpl.AssetsFS(), "favicon.png") if err != nil { s.serverError(w, err) return } w.Header().Set("Content-Type", "image/png") if !s.cfg.Dev { w.Header().Set("Cache-Control", "public, max-age=3600") } w.Write(data) }