From c91cdb80d03c5c2fe6f59d743cb04a3cd27311d7 Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Mon, 30 Mar 2020 09:47:21 +0200 Subject: [PATCH] Add option to update slug --- main.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/main.go b/main.go index 099f739..86bf4a2 100644 --- a/main.go +++ b/main.go @@ -51,6 +51,7 @@ func main() { r := mux.NewRouter() r.HandleFunc("/s", ShortenHandler) + r.HandleFunc("/u", UpdateHandler) r.HandleFunc("/d", DeleteHandler) r.HandleFunc("/{slug}", ShortenedUrlHandler) r.HandleFunc("/", CatchAllHandler) @@ -130,6 +131,38 @@ func ShortenHandler(w http.ResponseWriter, r *http.Request) { writeShortenedUrl(w, slug) } +func UpdateHandler(w http.ResponseWriter, r *http.Request) { + if !checkPassword(w, r) { + return + } + + slug := r.URL.Query().Get("slug") + if slug == "" { + http.Error(w, "Specify the slug to update", http.StatusBadRequest) + return + } + + newUrl := r.URL.Query().Get("new") + if newUrl == "" { + http.Error(w, "Specify the new URL", http.StatusBadRequest) + return + } + + if err, e := slugExists(slug); !e || err != nil { + http.Error(w, "Slug not found", http.StatusNotFound) + return + } + + _, err := db.Exec("UPDATE redirect SET url = ? WHERE slug = ?", newUrl, slug) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte("Slug updated")) +} + func DeleteHandler(w http.ResponseWriter, r *http.Request) { if !checkPassword(w, r) { return