forked from ring-clojure/ring
/
file.clj
29 lines (26 loc) · 1.12 KB
/
file.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
(ns ring.middleware.file
"Static file serving."
(:require [ring.util.codec :as codec]
[ring.util.response :as response])
(:import java.io.File))
(defn- ensure-dir
"Ensures that a directory exists at the given path, throwing if one does not."
[^String dir-path]
(let [dir (File. dir-path)]
(if-not (.exists dir)
(throw (Exception. (format "Directory does not exist: %s" dir-path))))))
(defn wrap-file
"Wrap an app such that the directory at the given root-path is checked for a
static file with which to respond to the request, proxying the request to the
wrapped app if such a file does not exist.
An map of options may be optionally specified. These options will be passed
to the ring.util.response/file-response function."
[app ^String root-path & [opts]]
(ensure-dir root-path)
(let [opts (merge {:root root-path, :index-files? true, :allow-symlinks? false} opts)]
(fn [req]
(if-not (= :get (:request-method req))
(app req)
(let [path (.substring ^String (codec/url-decode (:uri req)) 1)]
(or (response/file-response path opts)
(app req)))))))