Skip to content

Instantly share code, notes, and snippets.

@gtrak
Created June 30, 2013 21:09
Show Gist options
  • Save gtrak/5896906 to your computer and use it in GitHub Desktop.
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.
(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