morffix/server/file.go
2024-06-22 22:16:21 +02:00

57 lines
1.6 KiB
Go

package server
import (
"log/slog"
"net/http"
"path/filepath"
)
func handleFile(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.Error(w, "No id", http.StatusBadRequest)
return
}
// TODO check if worker is working on a task involving this file
var fpath string
var libraryID int
err := db.QueryRow(r.Context(), "SELECT path, library_id FROM files WHERE id = $1", id).Scan(&fpath, &libraryID)
if err != nil {
http.Error(w, "Error Getting File Path: "+err.Error(), http.StatusBadRequest)
slog.ErrorContext(r.Context(), "Getting File Path", "err", err)
return
}
var lpath string
err = db.QueryRow(r.Context(), "SELECT path FROM libraries WHERE id = $1", libraryID).Scan(&lpath)
if err != nil {
http.Error(w, "Error Getting Library Path: "+err.Error(), http.StatusBadRequest)
slog.ErrorContext(r.Context(), "Getting Library Path", "err", err)
return
}
fullPath := filepath.Join(lpath, fpath)
slog.InfoContext(r.Context(), "Serving File Download", "id", id, "path", fullPath)
// had timeout issues
http.ServeFile(w, r, fullPath)
/*
reader, err := os.Open(fullPath)
if err != nil {
http.Error(w, "Error Opening File: "+err.Error(), http.StatusInternalServerError)
slog.ErrorContext(r.Context(), "Opening File", "err", err)
return
}
w.Header().Set("Content-Disposition", "attachment;filename="+filepath.Base(fullPath))
_, err = io.Copy(w, reader)
if err != nil {
http.Error(w, "Copy File: "+err.Error(), http.StatusBadRequest)
slog.ErrorContext(r.Context(), "Copy File", "err", err)
return
}
*/
}