Clojure Web Development Essentials
上QQ阅读APP看书,第一时间看更新

Configuring and running the Ring Server

There are two ways you can run the Ring Server. The first is by loading the hipstr.repl namespace into a REPL and calling start-server. The second is from the command line (which we've seen earlier):

# lein ring server

In either case, an embedded Jetty server will be spun up to serve our application handler, and a browser will pop open. If you don't want the browser to open, you can run the server in the headless mode:

# lein ring server-headless

How we start the server determines how we configure the server. We've already seen how to configure the server when running through the REPL (by adjusting the options map that's passed as part of the call to ring.server.standalone/serve), but how do we configure the server if running from the command line?

The lein ring command is made available through the lein-ring plugin. Luminus includes this plugin when generating the project for us. In our project dependencies file (project.clj), you'll see the following lines of code:

:plugins [[lein-ring "0.8.13"]
  [lein-environ "1.0.0"]
  [lein-ancient "0.5.5"]]

The plugin offers a few useful subtasks, but the immediately beneficial ones are the server and server-headless subtasks.

Both of these subtasks will use the same configuration, configured in our project.clj, immediately following the plugins section:

:ring {:handler hipstr.handler/app
  :init    hipstr.handler/init
  :destroy hipstr.handler/destroy}

The options map should look familiar, as it's nearly identical to the options map we pass into the call to ring.server.standalone/serve in the hipstr.repl namespace. The main difference is the :handler option, which points to our hipstr.handler/app application handler, whereas in the hipstr.repl namespace we pass the handler directly. In essence, running the Ring Server from the command line does what we do in hipstr.repl/start-server.

You can play around starting the Ring Server from the command line and specifying some additional options as defined at https://github.com/weavejester/ring-server#usage. For example, try setting the :open-browser? option to false.

:ring {:handler hipstr.handler/app
  :init hipstr.handler/init
  :destroy  hipstr.handler/destroy
:open-browser? false}

With :open-browser? set to false our lein ring server will no longer open a browser, much like lein ring server-headless.