morffix/server/file.go

63 lines
1.7 KiB
Go

package server
import (
"log/slog"
"net/http"
"path/filepath"
"git.lastassault.de/speatzle/morffix/constants"
)
func handleFile(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(constants.SHARED_SECRET_HEADER) != conf.SharedSecret {
w.WriteHeader(http.StatusUnauthorized)
return
}
id := r.PathValue("id")
if id == "" {
http.Error(w, "No id", http.StatusBadRequest)
return
}
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
}
*/
}