Monday, July 11, 2011

type-safe urls via web-routes, part 1

web-routes is a suite of libraries which provide "type-safe" web routing. Instead of working directly with url strings in your web application, you create types to represent the routes.

The web-routes library has been around for several years. The idea itself is fairly obvious to many Haskell programmers, and so the idea has been rediscovered many times.

web-routes is designed to be exceedingly flexible. It is not explicitly tied to any haskell web framework, templating system, etc. It forms the basis of type-safe urls in yesod. There is also support for Happstack and HSP.

web-routes does not impose any particular method of mapping the url types to strings. We provide a variety of ways to defining mappings via addons including quasi-quotation, template haskell, generics, parsec, and more. If none of these systems suit your fancy, you can easily provide your own system. You basically need to provide two functions:

urlToString :: url -> [(String, String)] -> [String]
stringToUrl :: [String] -> Either String url

If you have an idea for how to map urls to types, I would encourage you to consider basing it on web-routes. A significant amount of effort has gone into handling issues like unicode and url escaping (among other things). If you use web-routes you do not need to know *any* of those rules. web-routes takes care of all that nastiness for you. If you find that web-routes is not suitable for your needs, I would love to hear why and see if we can not fix it.

The biggest issue with web-routes has been the lack of good documentation. So, I am pleased to announce that the first in a series of tutorials on web-routes is now online at: http://happstack.com/docs/crashcourse/WebRoutes.html.

Comments, questions, and corrections appreciated!

2 comments:

  1. One thing that would immediately improve web-routes and the related packages is if they had correct requirements in their cabal files. :-) web-routes-wai, for instance, won't build at all and hasn't (as far as I can tell) since wai-0.2.2.1 (the switch to enumerator) and web-routes-0.22.0 (adding [(String, String)] to the String <-> URL functions). I tried to get it working but have given up.

    On the topic of the web-routes tutorial itself: it's great. Thanks

    ReplyDelete
  2. Sorry about that. I have updated web-routes-wai to the latest web-routes and latest wai, put the correct depends in the .cabal, and added a script that will let me know when the depends are out of date. Hopefully that should keep things in sync better.

    ReplyDelete