James Williams
LinkedInMastodonGithub

Create Lightweight Groovy Web Apps with Ratpack

Besides having one of the most awesome names for a Groovy project, well besides Griffon ;), Ratpack is a nice web framework to scaffold and prototype ideas.

Inspired by the Sinatra Ruby web framework, Ratpack puts routes (URL mappings) at the forefront. Compared to Grails, it's a more bootstraped experience but is useful for small projects. Just as Sinatra coexists with Rails, Ratpack can coexist with Grails.

Route Basics

Each route contains the code that will be executed when it is accessed. Here is a basic route that prints "Hello, World!" when someone navigates to localhost:5000/helloworld:

get("/helloworld") {
    "Hello, World!"
}

Behind the scenes, there is a handler that is injecting a HttpServletRequest and HttpServletResponse for us to interact with. That means that you don't have to learn a new protocol and you can leverage your Java Servlet knowledge. To further illustrate this, any of the following routes would work as well:

get("/") {
    response.sendRedirect("/helloworld")
}
get("/error/:error") {
    response.sendError(new Integer(urlparams.error))
}
get("/data") {
    request.toString()
}

We can see from the error route that the :variableName notation gives us an equivalent to $variableName in Grails. They aren't listed here for brevity but any of the HTTP verbs can be routed to.

Running Ratpack

After downloading the package from Github at https://github.com/bleedingwolf/Ratpack, you'll need to run the gradle task

gradle deployRatpack

This retrieves Jetty and other dependencies, compiles the framework, and drops all the libs into your .groovy/libs directory. I haven't had any problems with these libraries specifically but in the past libs in the .groovy directory have caused version conflicts, so just be aware. After you have the libs installed, you can run Ratpack in two different ways. Static mode uses a bash script named ratpack and any changes to files won't be picked up until you bounce the server.

ratpack <application file>

Dynamic mode operates similar to grails run-app in dev mode bouncing the server automatically when a file in the watched directory is changed:

groovy <RatpackDir>scripts/runapp.groovy <app file> <dir to monitor>

Drop the code from the two code snippets in a file and you're off to the races. No import files needed.

It remains to be seen if an ecosystem of middleware extensions as vibrant as Sinatra or Node.js builds around it but I'm looking forward to playing more with Ratpack.