I have a static file called index.html
that I\'d like to serve when someone requests /
. Usually web servers do this by default, but Compojure doesn
This would be a pretty simple Ring middleware:
(defn wrap-dir-index [handler]
(fn [req]
(handler
(update-in req [:uri]
#(if (= "/" %) "/index.html" %)))))
Just wrap your routes with this function, and requests for /
get transformed into requests for /index.html
before the rest of your code sees them.
(def app (-> (routes (your-dynamic-routes)
(resources "/"))
(...other wrappers...)
(wrap-dir-index)))
This works just fine. No need to write a ring middle-ware.
(:require [clojure.java.io :as io])
(defroutes app-routes
(GET "/" [] (io/resource "public/index.html")))
when other code doesnt work, try this code.
(GET "/about/" [] (ring.util.response/content-type
(ring.util.response/resource-response "about/index.html" {:root "public"}) "text/html"))
(ns compj-test.core
(:use [compojure.core])
(:require
[ring.util.response :as resp]))
(defroutes main-routes
(GET "/" [] (resp/redirect "/index.html")))
What you're asking for is a redirect from / to /index.html. Its as simple as (resp/redirect target). No need to over complicate things.
Just a consideration Binita, a gotcha I have been experiencing. Despite I couldn't find any documentation regarding importance of order defining Compojure routes I find out that this doesn't work
(GET "/*" [] r/static)
(GET "/" [] (clojure.java.io/resource "public/index.html"))
while this does work
(GET "/" [] (clojure.java.io/resource "public/index.html"))
(GET "/*" [] r/static)
Obviously the *
matchs also the empty string but I thought that the order shouldn't matter at all.
After viewing a lot of the answers here, I'm using the following code:
(ns app.routes
(:require [compojure.core :refer [defroutes GET]]
[ring.util.response :as resp]))
(defroutes appRoutes
;; ...
;; your routes
;; ...
(GET "/" []
(resp/content-type (resp/resource-response "index.html" {:root "public"}) "text/html"))))
Check ring-defaults. It has best practices middleware you should use on your projects.