Created
June 30, 2013 21:09
-
-
Save gtrak/5896906 to your computer and use it in GitHub Desktop.
Simple HTML URL rewriting using compojure/laser, relativizing to a servlet-context path.
This file contains 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
(defn add-context-fn | |
[attr context] | |
(fn [node] | |
(update-in | |
node | |
[:attrs attr] | |
(fn [val] | |
(let [val (str val)] | |
(if (or (-> val java.net.URI. .isAbsolute) | |
(.startsWith val "//") | |
;; catches path-relative urls | |
(not (.startsWith val "/"))) | |
val | |
(str context val))))))) | |
(defn relativize | |
[content context] | |
(if-not context | |
content | |
(laser/document | |
(laser/parse content) | |
(laser/element= :a) (add-context-fn :href context) | |
(laser/element= :link) (add-context-fn :href context) | |
(laser/element= :script) (add-context-fn :src context)))) | |
(defn html [path] | |
(content-type/wrap-content-type | |
(GET path {context :context} | |
(if-let [r (io/resource (str "public/" path))] | |
(rr/response (-> (slurp r) | |
(relativize context))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment