From 3acf4e857fe67922b8771bba46496a648f19b06f Mon Sep 17 00:00:00 2001 From: Jacob McDonnell Date: Sun, 19 Apr 2026 19:48:45 -0400 Subject: feat: Check if short URL already Exists --- .gitignore | 1 + README.md | 2 -- main.go | 33 ++++++++++++++++++++++++--------- 3 files changed, 25 insertions(+), 11 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0f93a91 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +url-shortener diff --git a/README.md b/README.md index 679baac..e1929bf 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,6 @@ Response JSON: `{ "Version" : string, "Status" : string, "Original" : string, "N - Check API Keys for `/shorten` -- Check if URL is already Shortened - - Connect to a database for persisent storage - Better Error Handling diff --git a/main.go b/main.go index 11d7370..a43b510 100644 --- a/main.go +++ b/main.go @@ -51,13 +51,36 @@ func redirect(w http.ResponseWriter, r *http.Request) { original, ok := Table[url] if ok { + log.Println("Found:", original) + w.Header().Set("location", original) http.Error(w, http.StatusText(301), 301) } else { + log.Println("Unable to find website for", url) http.Error(w, http.StatusText(404), 404) } } +func FindOrGenerate(url string) string { + for key, value := range Table { + if value == url { + return key + } + } + + short := GenerateString(4) + _, ok := Table[short] + + for ok { + short = GenerateString(4) + _, ok = Table[short] + } + + Table[short] = url + + return short +} + func shorten(w http.ResponseWriter, r *http.Request) { log.Println("Request to Shorten") log_header(r) @@ -67,15 +90,7 @@ func shorten(w http.ResponseWriter, r *http.Request) { http.Error(w, http.StatusText(500), 500) } - url := GenerateString(4) - _, ok := Table[url] - - for ok { - url = GenerateString(4) - _, ok = Table[url] - } - - Table[url] = request.URL + url := FindOrGenerate(request.URL) response := Response{version, "ok", request.URL, url} -- cgit v1.2.3