Articles

Namespaces

In the grand tradition of Clojure libraries we begin with an irrelevant quote.

Bi-directional URI dispatch. Like Compojure, but when you want to go both ways. If you are serving REST resources, you should be providing links to other resources, and without full support for forming URIs from handlers your code will become coupled with your routing. In short, hard-coded URIs will eventually break.

In bidi, routes are data structures, there are no macros here. Generally speaking, data structures are to be preferred over code structures. When routes are defined in a data structure there are numerous advantages - they can be read in from a configuration file, generated, computed, transformed by functions and introspected - all things which macro-based DSLs make harder.

For example, suppose you wanted to use the same set of routes in your application and in your production Nginx or HAProxy configuration. Having your routes defined in a single data structure means you can programmatically generate your configuration, making your environments easier to manage and reducing the chance of discrepancies.

bidi also avoids 'terse' forms for the route definitions- reducing the number of parsing rules for the data structure is valued over convenience for the programmer. Convenience can always be added later with macros.

Finally, the logic for matching routes is separated from the responsibility for handling requests. This is an important architectural principle. So you can match on things that aren't necessarily handlers, like keywords which you can use to lookup your handlers, or whatever you want to do. Separation of concerns and all that.

bidi is written to do 'one thing well' (URI dispatch and formation) and is intended for use with Ring middleware, HTTP servers (including Jetty, http-kit and aleph) and is fully compatible with Liberator.

Version 2.x builds on 1.x by providing a mechanism to envelope multiple virtual hosts with a single route map. The idea is to eventually create a route map which defines routes across multiple services and helps with the construction of URIs to other services, a process which is traditionally error-prone.

Version 2.x is backward compatible and forward compatible with version 1.x. If you are upgrading from 1.x to 2.x you will not need to change your existing route definitions.

We have a match! A map is returned with a single entry with a :handler key and :index as the value. We could use this result, for example, to look up a Ring handler in a map mapping keywords to Ring handlers.

What happens if we try a different path?

user> (match-route route "/another.html")
nil

We get a nil. Nil means 'no route matched'.

Now, let's go in the other direction.

user> (path-for route :index)
"/index.html"

We ask bidi to use the same route definition to tell us the path that would match the :index handler. In this case, it tells us /index.html. So if you were forming a link to this handler from another page, you could use this function in your view logic to create the link instead of hardcoding in the view template (This gives your code more resilience to changes in the organisation of routes during development).

Now let's suppose we have 2 routes. We match partially on their common prefix, which in this case is "/" but we could use "" if there were no common prefix. The patterns for the remaining path can be specified in a map (or vector of pairs, if order is important).

It's common to want to match on a pattern or template, extracting some variable from the URI. Rather than including special characters in strings, we construct the pattern in segments using a Clojure vector [:id "/article.html"]. This vector replaces the string we had in the left hand side of the route pair.

Match results can be any value, but are typically functions (either in-line or via a symbol reference). You can easily wrap your routes to form a Ring handler (similar to what Compojure's routes and defroutes does) with the make-handler function.

We've already seen how keywords can be used to extract segments from a path. By default, keywords only capture numbers and simple identifiers. This is on purpose, in a defence against injection attacks. Often you'll want to specify exactly what you're trying to capture using a regular expression.

If we want :id to match a number only, we can substitute the keyword with a pair, containing a regular expression followed by the keyword. For example, instead of this :-

By default, routes ignore the request method, behaving like Compojure's ANY routes. That's fine if your handlers deal with the request methods themselves, as Liberator's do. However, if you want to limit a route to a request method, you can wrap the route in a pair (or map entry), using a keyword for the pattern. The keyword denotes the request method (:get, :put, etc.)

Sometimes you want segments of the URI to be extracted as keywords rather than strings, and in the reverse direction, to use keywords as values to be encoded into URIs.

You can construct a pattern similarly to how you specify regular expressions but instead of the regex you use specify keyword core function.

[ "foo/" [ keyword :db/ident ] "/bar" ]

When matching the path foo/bidi/bar, the :route-params of the result would be {:db/ident :bidi}. To construct the path, you would use (path-for my-routes handler :db/ident :bidi), which results in foo/bidi/bar (the colon of the stringified keyword is omitted).

Namespaced keywords are also supported. Note that in the URI the / that separates the keyword's namespace from its name is URL encoded to %2F, rather than /.

The left-hand-side of a pair is the pattern. It can match a path, either fully or partially. The simplest pattern is a string, but other types of patterns are also possible, including segmented paths, regular expressions, records, in various combinations.

The right-hand-side indicates the result of the match (in the case that the pattern is matched fully) or a route sub-structure that attempts to match on the remainder of the path (in the case that the pattern is matched partially). The route structure is a recursive structure.

This BNF grammar formally defines the basic route structure, although it is possible extend these definitions by adding types that satisfy the protocols used in bidi (more on this later).

It's just like the vector-of-vectors syntax we've seen before in bidi, but this time the first element is a virtual-host declaration. This is usually a string but can also be a java.net.URI or java.net.URL, or a map like {:scheme :https :host "example.org:8443"}.

A virtual-hosts super-structure is created with the bidi.vhosts/vhosts.model variadic function, each argument is a virtual-host structure.

A partially applied uri-info function is available in bidi's matching context and returns a map of the following elements. This partial applies the vhosts-model which can help with dependency cycles in your code (where your bidi router requires knowledge of resources, which have views that require knowledge of the bidi router's routes).

When called via bidi's match-context, the :href entry in the result may not contain the scheme, host and port, if these are redundant, whereas the :uri entry always contains an absolute URI. If you are creating HTML content for a browser, :href is safe to use. If, for example, you are creating an API returning a JSON-formatted response body, prefer :uri.

The rules for uri-info are that the first virtual-host in the vector is used. When the request is known to bidi (i.e. in the partially applied uri-info function in the match-context) the algorithm chooses the first virtual host that matches the request URI's scheme.

As they are simply nested data structures (strings, vectors, maps), route structures are highly composable. They are consistent and easy to generate. A future version of bidi may contain macros to reduce the number of brackets needed to create route structures by hand.

The implementation is based on Clojure protocols which allows the route syntax to be extended outside of this library.

Built-in records are available but you can also create your own. Below is a description of the built-in ones and should give you an idea what is possible. If you add your own types, please consider contributing them to the project. Make sure you test that your types in both directions (for URI matching and formation).

Any requests to /articles/old yield 307 Temporary Redirect responses with a Location header of /articles/new. This is a robust way of forming redirects in your code, since it guarantees that the Location URI matches an existing handler, both reducing the chance of broken links and encouraging the practise of retaining old URIs (linking to new ones) after refactoring. You can also use it for the common practice of adding a welcome page suffix, for example, adding index.html to a URI ending in /.

The Resources and ResourcesMaybe record can be used on the right-hand side of a route. It serves resources from the classpath. After the pattern is matched, the remaining part of the path is added to the given prefix.

["/resources" (->ResourcesMaybe {:prefix "public/"})

There is an important difference between Resources and ResourcesMaybe. Resources will return a 404 response if the resource cannot be found, while ResourcesMaybe will return nil, allowing subsequent routes to be tried.

Use this with caution. If you are using this you are probably doing it wrong.

Bidi separates URI routing from request handling. Ring middleware is something that should apply to handlers, not routes. If you have a set of middleware common to a group of handlers, you should apply the middleware to each handler in turn, rather than use ->WrapMiddleware. Better to map a middleware applying function over your handlers rather than use this feature.

Sometimes you need to apply a tag to a route, so you can use the tag (rather than the handler) in a path-for function. This is very convenient when forming routes, because you don't need to have a reference to the handler itself.

You can use the tag function to construct these records.

(tag my-handler :my-tag)

It's common to use the single threaded macro, so wrapping handlers in tags is just like wrapping them in Ring middleware. For example :-

It's possible to extract all possible routes from a route structure with route-seq.

Call route-seq on a route structure returns a sequence of all the possible routes contained in the route structure. This is useful to generating a site map. Each route is a map containing a path and a handler entry.

If you use keywords to extract route parameters, they will be contained in the path. If you wish to control the expansion, use a custom record that satisfies both bidi/Pattern and bidi/Matches.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.