From c62e2bbb5d8e27a037916d64dff7c9ffa4b61186 Mon Sep 17 00:00:00 2001 From: jabuxas Date: Tue, 29 Oct 2024 19:20:52 -0300 Subject: [PATCH] fix: logic on naming url with secret --- handlers.go | 14 +++++++------- helpers.go | 12 +++++++----- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/handlers.go b/handlers.go index f225b23..b581f39 100644 --- a/handlers.go +++ b/handlers.go @@ -158,11 +158,11 @@ func (app *Application) formHandler(w http.ResponseWriter, r *http.Request) { } defer file.Close() - filename := app.publicURL(file, ".txt") - + full := true if len(r.Form["secret"]) == 0 { - filename = filename[:8] + full = false } + filename := app.publicURL(file, ".txt", full) // reopening file because hash consumes it file, err = os.Open("/tmp/file.txt") @@ -198,11 +198,11 @@ func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) { } defer file.Close() - filename := app.publicURL(file, filepath.Ext(handler.Filename)) - + full := true if len(r.Form["secret"]) == 0 { - filename = filename[:8] + full = false } + filename := app.publicURL(file, filepath.Ext(handler.Filename), full) // reopen the file for copying, as the hash process consumed the file reader file, _, err = r.FormFile("file") @@ -219,7 +219,7 @@ func (app *Application) curlHandler(w http.ResponseWriter, r *http.Request) { ResponseURLHandler(w, app.url, filename) } -func (app *Application) publicURL(file io.Reader, extension string) string { +func (app *Application) publicURL(file io.Reader, extension string, full bool) string { filename, _ := HashFile(file, extension) filepath := filepath.Join(app.filesDir, filename) diff --git a/helpers.go b/helpers.go index b4f2c40..a1423c8 100644 --- a/helpers.go +++ b/helpers.go @@ -67,17 +67,19 @@ func FormatFileSize(size int64) string { return fmt.Sprintf("%.2f GB", float64(size)/(1024*1024*1024)) } -func HashFile(file io.Reader, extension string) (string, error) { +func HashFile(file io.Reader, extension string, full bool) (string, error) { hasher := md5.New() if _, err := io.Copy(hasher, file); err != nil { return "", err } - sha1Hash := hex.EncodeToString(hasher.Sum(nil))[:8] - + sha1Hash := hex.EncodeToString(hasher.Sum(nil)) filename := fmt.Sprintf("%s%s", sha1Hash, extension) - - return filename, nil + if full { + return filename, nil + } else { + return fmt.Sprintf("%s%s", sha1Hash[:8], extension), nil + } } func SaveFile(name string, file io.Reader) error {