:destroy callback runs after server stop

This commit is contained in:
James Reeves 2012-02-11 20:12:28 +00:00
parent fb01783cfb
commit d960f97921
2 changed files with 30 additions and 13 deletions

View file

@ -12,18 +12,28 @@
(try-port port run-server) (try-port port run-server)
(throw ex)))))) (throw ex))))))
(defn- setup-callbacks [{:keys [init destroy]}] (defmacro ^:private in-thread [& body]
(if init (init)) `(doto (Thread. (fn [] ~@body))
(if destroy (.start)))
(. (Runtime/getRuntime)
(addShutdownHook (Thread. destroy))))) (defn- run-server [server destroy]
(in-thread
(try (.join server)
(finally (if destroy (destroy))))))
(defn serve (defn serve
"Start a web server to run a handler." "Start a web server to run a handler."
[handler & [{:as options}]] [handler & [{:keys [init destroy join?] :as options}]]
(setup-callbacks options) (let [options (assoc options :join? false)
(try-port (port options) destroy (if destroy (memoize destroy))]
(fn [port] (if init (init))
(run-jetty (if destroy
handler (. (Runtime/getRuntime)
(merge {:port port} options))))) (addShutdownHook (Thread. destroy))))
(try-port (port options)
(fn [port]
(let [options (merge {:port port} options)
server (run-jetty handler options)
thread (run-server server destroy)]
(if join? (.join thread))
server)))))

View file

@ -43,4 +43,11 @@
(testing ":init option" (testing ":init option"
(let [ran-init? (atom false)] (let [ran-init? (atom false)]
(with-server (test-server {:init #(reset! ran-init? true)}) (with-server (test-server {:init #(reset! ran-init? true)})
(is @ran-init?))))) (is @ran-init?))))
(testing ":destroy option"
(let [ran-destroy? (atom false)]
(with-server (test-server {:destroy #(reset! ran-destroy? true)})
(is (not @ran-destroy?)))
(Thread/sleep 100)
(is @ran-destroy?))))