1
Fork 0

Allow deleting slugs

This commit is contained in:
Jan-Lukas Else 2020-03-29 12:47:35 +02:00
parent c05a90d9c4
commit 9a22f4b3e5
1 changed files with 34 additions and 0 deletions

34
main.go
View File

@ -52,6 +52,7 @@ func main() {
r := mux.NewRouter()
r.HandleFunc("/s", ShortenHandler)
r.HandleFunc("/d", DeleteHandler)
r.HandleFunc("/{slug}", ShortenedUrlHandler)
r.HandleFunc("/", CatchAllHandler)
@ -136,6 +137,39 @@ func ShortenHandler(w http.ResponseWriter, r *http.Request) {
writeShortenedUrl(w, slug)
}
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
password := r.URL.Query().Get("password")
if password != viper.GetString("password") {
http.Error(w, "Wrong password", http.StatusBadRequest)
return
}
slug := r.URL.Query().Get("slug")
if slug == "" {
http.Error(w, "Specify the slug to delete", http.StatusBadRequest)
return
}
if err, e := slugExists(slug); !e || err != nil {
http.Error(w, "Slug not found", http.StatusNotFound)
return
}
stmt, err := db.Prepare("DELETE FROM redirect WHERE slug = ?")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = stmt.Exec(slug)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
_, _ = w.Write([]byte("Slug deleted"))
}
func generateSlug() string {
var chars = []rune("0123456789abcdefghijklmnopqrstuvwxyz")
s := make([]rune, 6)