Skip to content

Instantly share code, notes, and snippets.

@tdantas
Created April 12, 2016 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdantas/3becce58e0752c46b9fd59833c93390b to your computer and use it in GitHub Desktop.
Save tdantas/3becce58e0752c46b9fd59833c93390b to your computer and use it in GitHub Desktop.
shortner
;;adambard
(ns urlshortener.core
(:require
[org.httpkit.server :refer [run-server]]
[taoensso.carmine :as redis])
(:import
clojure.lang.Murmur3
org.apache.commons.validator.routines.UrlValidator))
(def validator (UrlValidator. (into-array ["http" "https"])))
(def hash-url (comp (partial format "%x")
#(Murmur3/hashUnencodedChars %)))
(defn create-short-url [path]
(let [rand-str (hash-url path)]
(redis/wcar nil
(redis/set (str "/" rand-str) path))
(str "http://mydomain.com/" rand-str)))
(defn handle-create [{path :uri :as request}]
(if (.isValid validator (apply str (rest path)))
{:status 200 :body (create-short-url path)}
{:status 401 :body "Invalid Url provided"}))
(defn handle-redirect [{path :uri :as request}]
(let [url (redis/wcar nil (redis/get path))]
(if url
{:status 302 :body "" :headers {"Location" url}}
{:status 404 :body "Unknown destination."})))
(defn handler [{method :request-method :as req}]
(case method
:get (handle-redirect req)
:post (handle-create req)))
(run-server handler {:port 8080})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment