magpiebrain

The blog of Sam Newman. A Software Developer in London.

Using Scala pattern matching to implement a URL handler

I’ve been playing around with using Scala’s pattern matching support to create a URL handler for use with an embedded Jetty server. This little code snippet creates a Jetty handler that can not only match URLs, but even extract parts of the URL and pass it into the block

protected class SomeHandler extends AbstractHandler {
  override def handle(target: String, request: HttpServletRequest, response: HttpServletResponse) = {
    response.setContentType("text/html");
    val HomePage = "/"
    val StaticResources = new Regex("""/static/(.*)""")
   
    target match {
      case HomePage => {
        ok(response, "Hello!")
      } 
   
      case StaticResources(resource) => {
        ok(response, "You asked for resource " + resource)       
      }
	
      case _ => {           
        notFound(response, "Not Found")       
      }     
    }     
    (request.asInstanceOf[Request]).setHandled(true);     
  }   
} 

The ok, notFound methods simply write the String out to the response stream with the right HTTP code.

The StaticResources regex pulls out everything after the /static/ root. It would be easy to imagine some kind of regex which pulled out the year, month and day from a URL - for example:

val EntriesOnDay = new Regex("""/posts/(\d+)/(\d+)/(\d+)""")
...

target match {
  case EntriesOnDay(year, month, day) => {
    // use year, month, day etc to pull back posts or whatever
  }
}
Comments (View)
blog comments powered by Disqus