Search code examples
clojurehttp-kit

How to reload (stop and start) an http-kit "mount state" on a -main function


With the mount library, how do I reload (stop and start) an http-kit "mount state" on a -main function?

My current code is this:

(defstate server-config :start {:port 7890 :join? false})
(defn start-server [server-config]
  (when-let [server (run-server myserv-ring-handler server-config)]
    (println "Server has started!")
    server))

(defstate myserv-server :start (start-server server-config)
          :stop  (myserv-server :timeout 100))

(defn system-port [args]
  (Integer/parseInt
    (or (System/getenv "PORT")
        (first args)
        "7890")))

(defn -main [& args]
  (mount/start-with-states
    {#'myserv/server-config
     {:start #(array-map :port (system-port args)
                         :join? false)}}))

So when I "lein run" everything works, but whenever I change a file, and the http-kit server is stopped, the command stops. For the moment I'm doing "while true; do lein run; done" to work, so I've thought about adding an infinite loop to the -main function, but it doesn't feel like this is the right way.

How should I do this?


Solution

  • So I had a couple of separate problems:

    • I didn't understand that now I didn't need to use lein run, but instead I could just do lein repl and start the server from there. The restarting problem is avoided that way.
    • The other one was that I was misusing start-with-states instead of a config state.

    You can see a discussion about this with the author of the library here.