code refactoring, added router, moved download api path

This commit is contained in:
2024-02-23 10:55:33 +01:00
parent 65b0c8bc0e
commit 1cfda047cb
20 changed files with 146 additions and 41 deletions

View File

@@ -2,7 +2,10 @@ package rest
import (
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"github.com/go-chi/chi/v5"
"github.com/marcopeocchi/yt-dlp-web-ui/server/internal"
@@ -173,3 +176,36 @@ func (h *Handler) DirectoryTree() http.HandlerFunc {
}
}
}
func (h *Handler) DownloadFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
w.Header().Set("Content-Type", "application/json")
id := chi.URLParam(r, "id")
path, err := h.service.DownloadFile(r.Context(), id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add(
"Content-Disposition",
"inline; filename="+filepath.Base(*path),
)
w.Header().Set(
"Content-Type",
"application/octet-stream",
)
fd, err := os.Open(*path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.Copy(w, fd)
}
}