package api import ( "fmt" "net/http" "strconv" ) func (a *API) HandleDownload(w http.ResponseWriter, r *http.Request) { idStr := r.PathValue("id") id, err := strconv.ParseInt(idStr, 10, 64) if err != nil { writeError(w, http.StatusBadRequest, "invalid image id") return } img, err := a.DB.GetImageByID(r.Context(), id) if err != nil { writeError(w, http.StatusNotFound, "image not found") return } f, err := a.Storage.Open(img.StoragePath) if err != nil { writeError(w, http.StatusNotFound, "file not found on disk") return } defer f.Close() w.Header().Set("Content-Type", img.MimeType) w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, img.Filename)) http.ServeContent(w, r, img.Filename, img.CreatedAt, f) }