From 6659c0b28f0d11d017a1ee8fb335b71837ad57e7 Mon Sep 17 00:00:00 2001 From: bain Date: Sun, 15 Oct 2023 13:08:19 +0200 Subject: [PATCH] allow multiple shortened links to a single URL closes NoLog.cz/gull#3 --- handlers/handlers.go | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/handlers/handlers.go b/handlers/handlers.go index 974e88f..aedbbae 100644 --- a/handlers/handlers.go +++ b/handlers/handlers.go @@ -17,7 +17,7 @@ type App struct { } type urlEntry struct { - URL string `gorm:"unique" json:"url"` + URL string `json:"url"` Alias string `gorm:"unique" json:"alias"` } @@ -67,18 +67,14 @@ func (a *App) CreateShortURL(w http.ResponseWriter, r *http.Request) { http.Error(w, "Invalid Alias", http.StatusBadRequest) return } - // Check if URL entry already exists - existingURL := &urlEntry{} - a.DB.Where("url = ?", u.URL).Find(existingURL) - if existingURL.URL != "" { - u.Alias = existingURL.Alias - } else { - // Verify alias is unique - for u.Alias == "" || !a.DB.Where("alias = ?", u.Alias).First(existingURL).RecordNotFound() { - u.Alias = utils.RandString(6) - } - a.DB.Create(u) - } + + // Verify alias is unique + existingURL := &urlEntry{} + for u.Alias == "" || !a.DB.Where("alias = ?", u.Alias).First(existingURL).RecordNotFound() { + u.Alias = utils.RandString(6) + } + a.DB.Create(u) + // Write HTTP Response shortlink := r.Host + "/s/" + u.Alias w.Header().Set("Content-Type", "application/json")