Skip to content

with routes macro

Johan Haleby edited this page Mar 25, 2016 · 10 revisions

with-routes! (found in stub-http.core) is a macro that is useful if you don't need to reuse the "server" instance returned by start!. You can pass both bindings and routes to the macro. The macro expose three bindings to the body of the macro: uri, port and server. In its simplest form it can be used by only specifying a route:

(with-routes!
      {"/something" {:status 200 :content-type "text/plan" :body "hello" }}
      (is (= "hello" (:body (client/get (str uri "/something"))))))

This will start the stub server on a free port (available via port). The server is started by the macro and is reached from the uri (as seen in the example).

Bindings

Another useful feature that with-routes! provides is to allow you to declare bindings. This is useful to make the code more compact and avoid an additional let statement. For example let's say you're reading a response from a file that you want to return as the response body. One way would be to do like this:

(let [body (read-file-from-disk ...)]
   (with-routes!
	 {"/something" {:status 200 :content-type "text/plan" :body body }}
	 (is (= "...." (:body (client/get (str uri "/something")))))))

but since you can also declare bindings form the macro you can also do like this:

(with-routes! [body (read-file-from-disk ...)]
	  {"/something" {:status 200 :content-type "text/plan" :body body }}
	  (is (= "...." (:body (client/get (str uri "/something"))))))
Clone this wiki locally