Reitit

1 minute read

Reitit

Reitit is a routing library that can provides fast and extensible routing on top of Ring. To use it we need to include it in the Ring application handler and provide it with a vector of routes.

 1(ns ring-demo.core
 2  (:require [reitit.ring :as reitit]
 3            [ring.adapter.jetty :as jetty]))
 4
 5(def routes 
 6  [["/" {:get get-handler}]])
 7
 8(def handler
 9  (reitit/ring-handler
10    (reitit/router routes)))
11
12(defn -main 
13  []
14  (jetty/run-jetty
15    handler
16    {:port 3000
17     :join? false}))

Each routes is declared using a vector where the first element is a string representing the route path, and the second element is a map which contains an operation and a function which handles this request.

Reitit also supports dynamic paths with embedded parameters.

1(def routes
2  [["/echo/:id"
3    {:get 
4      (fn [{{:keys [id]} :path-params}]
5        (response/ok (str "<p>id: " id "</p>")))}]])

Defaults

The second parameter of reitit/ring-handler is a optional default handler. We can create it using reitit/create-default-handler.

1(def handler
2  (reitit/ring-handler
3    (reitit/router routes)
4    (reitit/create-default-handler
5      {:not-found 
6        (constantly (response/not-found "404 - Page not found"))
7       :method-not-allowed
8        (constantly (response/method-not-allowed "405 - Not allowed"))})))

Reitit also provides create-resource-handler for serving static resources.

1(def handler
2  (reitit/ring-handler
3    (reitit/router routes)
4    (reitit/create-resource-handler {:path "/"})))