summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--README.md2
-rw-r--r--main.go33
3 files changed, 25 insertions, 11 deletions
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}