From cf595f338aebc097a070d75acc3f05557d0d6b90 Mon Sep 17 00:00:00 2001 From: Michael Hohn Date: Mon, 20 May 2024 14:27:50 -0700 Subject: [PATCH] wip: port FileDownload --- pkg/server/server.go | 30 +++++++++++++++++++++++++++--- pkg/storage/storage.go | 15 +++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/pkg/server/server.go b/pkg/server/server.go index e362bed..8b766ab 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -10,13 +10,13 @@ import ( "log" "log/slog" "net/http" + "path/filepath" "strconv" "strings" "mrvacommander/pkg/storage" "github.com/gorilla/mux" - "github.com/hohn/ghes-mirva-server/analyze" "github.com/hohn/ghes-mirva-server/api" co "github.com/hohn/ghes-mirva-server/common" ) @@ -237,11 +237,35 @@ func (c *CommanderSingle) DownloadResponse(w http.ResponseWriter, js co.JobSpec, } func (c *CommanderSingle) MirvaDownloadServe(w http.ResponseWriter, r *http.Request) { - // TODO Port this function from ghes-mirva-server vars := mux.Vars(r) slog.Info("File download request", "local_path", vars["local_path"]) - analyze.FileDownload(w, vars["local_path"]) + FileDownload(w, vars["local_path"]) +} + +func FileDownload(w http.ResponseWriter, path string) { + slog.Debug("Sending zip file with .sarif/.bqrs", "path", path) + + fpath, res, err := storage.ResultAsFile(path) + if err != nil { + http.Error(w, "Failed to read results", http.StatusInternalServerError) + return + } + // Set headers + fname := filepath.Base(fpath) + w.Header().Set("Content-Disposition", "attachment; filename="+fname) + w.Header().Set("Content-Type", "application/octet-stream") + + // Copy the file contents to the response writer + rdr := bytes.NewReader(res) + _, err = io.Copy(w, rdr) + if err != nil { + http.Error(w, "Failed to send file", http.StatusInternalServerError) + return + } + + slog.Debug("Uploaded file", "path", fpath) + } func (c *CommanderSingle) MirvaRequestID(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/storage/storage.go b/pkg/storage/storage.go index 19882de..2ef3183 100644 --- a/pkg/storage/storage.go +++ b/pkg/storage/storage.go @@ -195,3 +195,18 @@ func GetStatus(sessionid int, orl co.OwnerRepo) co.Status { defer mutex.Unlock() return status[co.JobSpec{ID: sessionid, OwnerRepo: orl}] } + +func ResultAsFile(path string) (string, []byte, error) { + fpath := path + if !filepath.IsAbs(path) { + fpath = "/" + path + } + + file, err := os.ReadFile(fpath) + if err != nil { + slog.Warn("Failed to read results file", fpath, err) + return "", nil, err + } + + return fpath, file, nil +}