Skip to content

Instantly share code, notes, and snippets.

@fridgei
Last active August 29, 2015 14:01
Show Gist options
  • Save fridgei/8b0e0aae0770fa0ae84f to your computer and use it in GitHub Desktop.
Save fridgei/8b0e0aae0770fa0ae84f to your computer and use it in GitHub Desktop.
(ns shortener.handler
(:use compojure.core)
(:require [compojure.handler :as handler]
[compojure.route :as route]
[clojure.java.jdbc :as j]))
(def db
{:classname "org.sqlite.JDBC"
:subprotocol "sqlite"
:subname "db/database.db"
})
(defn create-db []
(try (with-connection db
(create-table :short_url
[:id :int "PRIMARY KEY"]
[:url :text]))
(catch Exception e (println e))))
(create-db)
(def check-url-by-id [id]
(try (with-connection db
(with-query-results rs
[ (str "SELECT * FROM short_url WHERE id = " + id) ]
(do rs.first :url)))
(catch Exception e (str ""))))
(defn redirect-if-exists
"redirect to url or 404 if not found"
{:test #(do
(assert (=
(redirect-if-exists "http://www.derp.com")
'(redirect "http://www.derp.com")))
(assert (=
(redirect-if-exists "")
'(page-not-foud))))}
("" (page-not-found))
(x (redirect x)))
(test #'redirect-if-exists)
(defroutes app-routes
(GET "/:id" [id]
(let [url (check-url-by-id id)]
(redirect-if-exists id))))
(def app
(handler/site app-routes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment