Serve index.html at / by default in Compojure

前端 未结 8 1889
无人及你
无人及你 2020-12-28 14:19

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

相关标签:
8条回答
  • 2020-12-28 14:54

    Recently I discovered that @amalloy's answer doesn't work when the Clojure/Compojure app is run under Jetty or Tomcat as a .war. In this case :path-info needs to be updated. Also, I think this version will handle any route, not just the "root" route.

    (defn- wrap-dir-index [handler]
      (fn [request]
        (handler
         (let [k (if (contains? request :path-info) :path-info :uri) v (get request k)]
           (if (re-find #"/$" v)
             (assoc request k (format "%sindex.html" v))
             request)))))
    

    See also: https://groups.google.com/forum/#!msg/compojure/yzvpQVeQS3w/RNFkFJaAaYIJ

    UPDATED: Replaced example with a version that works.

    0 讨论(0)
  • 2020-12-28 15:01

    An alternative could be to create either a redirect or a direct response in an additional route. Like so:

    (ns compj-test.core
      (:use [compojure.core])
      (:require [compojure.route :as route]
                [ring.util.response :as resp]))
    
    (defroutes main-routes
      (GET "/" [] (resp/file-response "index.html" {:root "public"}))
      (GET "/a" [] (resp/resource-response "index.html" {:root "public"}))
      (route/resources "/")
      (route/not-found "Page not found"))
    

    The "/" route returns a file response of "index.html" which is present in the public folder. The "/a" route responds directly by 'inlineing' the file index.html.

    More on ring responses: https://github.com/mmcgrana/ring/wiki/Creating-responses

    EDIT: removed unnecessary [ring.adapter.jetty] import.

    0 讨论(0)
提交回复
热议问题