diff --git a/src/ring/server/options.clj b/src/ring/server/options.clj index 8292f75..74ac9df 100644 --- a/src/ring/server/options.clj +++ b/src/ring/server/options.clj @@ -1,8 +1,13 @@ (ns ring.server.options "Functions to retrieve options and settings with sensible defaults" - (:use [ring.util.environment :only (*env*)] + (:use ring.util.environment + ring.middleware.stacktrace + ring.middleware.reload [clojure.core.incubator :only (-?>)])) +(def dev-env? + (not (*env* "LEIN_NO_DEV"))) + (defn port "Find the port or list of ports specified in the options or environment. Defaults to a range of ports from 3000 to 3010." @@ -15,4 +20,10 @@ "True if a browser should be opened to view the web server. By default a browser is opened unless the LEIN_NO_DEV environment variable is set." [options] - (:open-browser? options (not (*env* "LEIN_NO_DEV")))) + (:open-browser? options dev-env?)) + +(defn middleware + [options] + (or (:middleware options) + (if dev-env? + [wrap-stacktrace wrap-reload]))) diff --git a/src/ring/server/standalone.clj b/src/ring/server/standalone.clj index 4c0b79b..1dffbf7 100644 --- a/src/ring/server/standalone.clj +++ b/src/ring/server/standalone.clj @@ -47,11 +47,18 @@ (try (.join server) (finally (if destroy (destroy)))))) +(defn- add-middleware [handler options] + (reduce + (fn [h m] (m h)) + handler + (middleware options))) + (defn serve "Start a web server to run a handler." [handler & [{:keys [init destroy join?] :as options}]] (let [options (assoc options :join? false) - destroy (if destroy (memoize destroy))] + destroy (if destroy (memoize destroy)) + handler (add-middleware handler options)] (if init (init)) (if destroy (. (Runtime/getRuntime) diff --git a/test/ring/server/test/standalone.clj b/test/ring/server/test/standalone.clj index 716e0dd..a7a78ed 100644 --- a/test/ring/server/test/standalone.clj +++ b/test/ring/server/test/standalone.clj @@ -11,13 +11,23 @@ ~@body (finally (.stop server#))))) +(defn default-handler [req] + (response "Hello World")) + +(defn error-handler [req] + (throw (Exception. "testing"))) + (defn test-server [& [{:as options}]] - (let [handler (constantly (response "Hello World"))] + (let [handler (:handler options default-handler)] (serve handler (merge {:join? false, :open-browser? false} options)))) +(defn http-get [port uri] + (http/get (str "http://localhost:" port uri) + {:conn-timeout 1000 + :throw-exceptions false})) + (defn is-server-running-on-port [port] - (let [resp (http/get (str "http://localhost:" port) - {:conn-timeout 1000})] + (let [resp (http-get port "")] (is (= (:status resp) 200)))) (deftest serve-test @@ -50,4 +60,9 @@ (with-server (test-server {:destroy #(reset! ran-destroy? true)}) (is (not @ran-destroy?))) (Thread/sleep 100) - (is @ran-destroy?)))) + (is @ran-destroy?))) + + (testing "default middleware" + (with-server (test-server {:handler error-handler}) + (let [body (:body (http-get 3000 ""))] + (is (re-find #"java\.lang\.Exception: testing" body))))))