(ns bitgloo-web.core (:gen-class) (:require [bitgloo-web.content :as content]) (:require [clojure.java.io :as io]) (:require [clojure.string :as str]) (:require [ring.adapter.jetty :refer [run-jetty]]) (:require [ring.middleware.resource :refer [wrap-resource]]) (:require [ring.middleware.content-type :refer [wrap-content-type]]) (:require [ring.middleware.not-modified :refer [wrap-not-modified]]) (:require [ring.util.response :as resp])) (def not-found (resp/not-found "Not found")) (def image-extensions [".jpg" ".bmp"]) (defn image? [path] (some (partial str/ends-with? path) image-extensions)) (defn home-redirect [uri] (if (= "/" uri) "/home" uri)) (defn request-handler [content-path request] (let [path (str content-path (home-redirect (:uri request)))] (when-let [content (content/load-page path)] (-> (resp/response content) (resp/content-type "text/html") (resp/charset "utf8"))))) (defn wrap-content-images [handler content-path] (fn [request] (let [uri (:uri request) path (str content-path uri)] (if (image? uri) (when (.exists (io/file path)) (resp/file-response path)) (handler request))))) (defn wrap-only-gets [handler] (fn [request] (when (= :get (:request-method request)) (handler request)))) (defn wrap-log-transactions [handler] (fn [request] (let [response (handler request)] (println (get-in request [:headers "x-forwarded-for"]) "-" (str (java.util.Date.)) "-" (:request-method request) (:uri request) (:protocol request) "-" (:status response)) response))) (defn wrap-not-found [handler] (fn [request] (or (handler request) not-found))) (defn -main [& args] (if (= 2 (count args)) (let [port (-> args first Integer/parseInt) content-path (second args)] (-> (partial request-handler content-path) (wrap-content-images content-path) (wrap-resource "public") (wrap-content-type) (wrap-not-modified) (wrap-only-gets) (wrap-not-found) (wrap-log-transactions) (run-jetty {:port port}))) (println "usage: bitgloo port content-path")))