allow multiple shortened links to a single URL

closes NoLog.cz/gull#3
This commit is contained in:
bain 2023-10-15 13:08:19 +02:00
parent 436765613f
commit 6659c0b28f
Signed by: bain
GPG key ID: 31F0F25E3BED0B9B

View file

@ -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
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")