Created
April 12, 2016 16:25
-
-
Save tdantas/3becce58e0752c46b9fd59833c93390b to your computer and use it in GitHub Desktop.
shortner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;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