with routes macro

Johan Haleby edited this page Mar 27, 2016 · 9 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!](start! function). 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 of with-routes! is the ability to declare bindings. This makes the code more compact and may avoid an additional let statement. For example let's say you're serializing a map to a JSON string that you want to return as the response body. One way would be to do like this:

(let [body (json/generate-string {:hello "world"})]
   (with-routes!
	 {"/something" {:status 200 :content-type "text/plan" :body body }}
	 (is (= "world" (->> (client/get (str uri "/something")) :body :hello)))))

but since with-routes! also allows you to declare bindings you can do like this:

(with-routes! [body (json/generate-string {:hello "world"})]
	  {"/something" {:status 200 :content-type "text/plan" :body body }}
	  (is (= "world" (->> (client/get (str uri "/something")) :body :hello))))

which is less verbose.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.