sibiro.core

Simple data-driven request routing for Clojure and ClojureScript.

compile-routes

(compile-routes routes & {:as opts})
Compiles a routes datastructure for use in `match-uri` and
`uri-for`. Routes is a sequence of sequences (e.g. a vector of
vectors) containing 3 or 4 elements: a method keyword (or :any), a
clout-like path, a result object (can be a handler), and optionally
a tag. For example:

[[:get  "/admin/user/" user-list]
 [:get  "/admin/user/:id" user-get :user-page]
 [:post "/admin/user/:id" user-update]
 [:any  "/:*" handle-404]]

The order in which the routes are specified does not matter. Longer
routes always take precedence, exact uri parts take precedence over
route parameters, catch-all (:*) is tried last, and specific request
methods take precedence over :any.

Compiling takes some optional keyword arguments:

 :uri-for-tagged-only? - When set to true, only tagged routes are
   compiled for use with `uri-for` and can only be found by their
   tag. Defaults to false.

The routes are compiled into a tree structure, for fast matching.
Functions for creating URIs (`uri-for`) are also precompiled for
every route.

match-uri

(match-uri compiled uri request-method)
Given compiled routes, an URI and a request-method, returns
{:route-handler handler, :route-params {...}, :alternatives (...)}
for a match, or nil. For example:

(match-uri (compile-routes [[:post "/admin/user/:id" :update-user]
                            [:post "/admin/*"        :admin-catch]])
           "/admin/user/42" :post)
;=> {:route-handler :update-user, :route-params {:id "42"}
     :alternatives ({:route-handler :admin-catch, :route-params {:* "user/42"}})}

The values in :route-params are URL decoded for you.
The :alternatives value is lazy, so it won't search for alternatives
if you don't ask for it.

path-for

(path-for compiled handler)(path-for compiled handler params)(path-for compiled tag)(path-for compiled tag params)
Convenience method concatenating :uri and :query-string from
`uri-for`.

uri-for

(uri-for compiled handler)(uri-for compiled handler params)(uri-for compiled tag)(uri-for compiled tag params)
Given compiled routes and a handler (or tag), and optionally
parameters, returns {:uri "...", :query-string "?..."}. For
example:

(uri-for (compile-routes [[:post "/admin/user/:id" :update-user]])
         :update-user {:id 42 :name "alice"})
;=> {:uri "/admin/user/42", :query-string "?name=alice"}

An exception is thrown if parameters for the URI are missing in the
data map. The values in the data map are URL encoded for you.