internal/api/download.go (view raw)
1package api
2
3import (
4 "fmt"
5 "net/http"
6 "strconv"
7)
8
9func (a *API) HandleDownload(w http.ResponseWriter, r *http.Request) {
10 idStr := r.PathValue("id")
11 id, err := strconv.ParseInt(idStr, 10, 64)
12 if err != nil {
13 writeError(w, http.StatusBadRequest, "invalid image id")
14 return
15 }
16
17 img, err := a.DB.GetImageByID(r.Context(), id)
18 if err != nil {
19 writeError(w, http.StatusNotFound, "image not found")
20 return
21 }
22
23 f, err := a.Storage.Open(img.StoragePath)
24 if err != nil {
25 writeError(w, http.StatusNotFound, "file not found on disk")
26 return
27 }
28 defer f.Close()
29
30 w.Header().Set("Content-Type", img.MimeType)
31 w.Header().Set("Content-Disposition",
32 fmt.Sprintf(`attachment; filename="%s"`, img.Filename))
33 http.ServeContent(w, r, img.Filename, img.CreatedAt, f)
34}