From 324ee663d30d4529e91815f076aca53f8945a13c Mon Sep 17 00:00:00 2001 From: Matthew Lemon Date: Tue, 12 Mar 2024 09:25:35 +0000 Subject: wip: writes contents of uploaded csv file to http.ResponseWriter --- cmd/api/datamaps.go | 40 ++++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/cmd/api/datamaps.go b/cmd/api/datamaps.go index 6bbda2b..0d769e4 100644 --- a/cmd/api/datamaps.go +++ b/cmd/api/datamaps.go @@ -4,7 +4,6 @@ import ( "fmt" "io" "net/http" - "os" "strconv" ) @@ -24,22 +23,39 @@ func (app *application) createDatamapHandler(w http.ResponseWriter, r *http.Requ } defer file.Close() - // create a new file on the server - outFile, err := os.Create("uploaded.csv") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - defer outFile.Close() + // // create a new file on the server + // outFile, err := os.CreateTemp("", "uploaded_csv") + // if err != nil { + // http.Error(w, err.Error(), http.StatusInternalServerError) + // return + // } + // // clean up - we have to do this + // defer os.Remove(outFile.Name()) - // copy the uploaded file to the server file - _, err = io.Copy(outFile, file) + // // copy the uploaded file to the server file + // _, err = io.Copy(outFile, file) + // if err != nil { + // http.Error(w, err.Error(), http.StatusInternalServerError) + // return + // } + + // var b []byte // this doesn't work + // _, err = outFile.Read(b) + // if err != nil { + // http.Error(w, err.Error(), http.StatusInternalServerError) + // return + // } + // fmt.Fprintf(w, string(b)) + + // Read the contents of the file + fileBytes, err := io.ReadAll(file) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } - - fmt.Fprintf(w, "File uploaded successfully") + // Write the file contents to the response + w.Header().Set("Content-Type", "text/csv") // Set the appropriate content type + w.Write(fileBytes) } func (app *application) showDatamapHandler(w http.ResponseWriter, r *http.Request) { -- cgit v1.2.3