Posts‎ > ‎

A Groovy Webserver running on Raspberry Pi in minutes

posted Jan 2, 2015, 5:06 PM by Renato Athaydes
I have just bought a Raspberry Pi to have some fun with code first and, hopefully, hardware later.

After setting it up (with the Raspian OS, a Linux distro for the Pi), making sure it could connect to the internet and I could ssh into it from my laptop, the first thing I wanted to do was to get it to run a little webserver.

I have recently attended a Java meetup (in fact, the very first one in Stockholm) where one of the speakers demoed the Spark-Java micro-framework, and it really caught my attention. Starting up a webserver and providing a simple REST API or just plain HTML with it is as easy as it gets so I wanted to use that.

But is it that easy on the Pi? Well, if you're using Java, you would need to first, somehow, get the required jars, then compile all sources before you can run anything. It's not fun to manually download jars, place the files in the right places so that you can give java and javac the right classpath and so on, specially in an environment where an IDE is not a viable option... There should be a better way. And of course, there is!

I have already written about how easy it is to setup a webserver using Groovy, so I was already inclined to use Groovy for this... you see, using @Grab, all your dependencies will be downloaded automatically. No need to install Maven or Gradle! All you need, besides the JDK (which already comes installed in the Raspian image), is to have Groovy installed.

Now, you may ask, just how easy is it to install Groovy in the Raspberry Pi? Well, here's what you need to type in the terminal to get the job done:
curl -s get.gvmtool.net | bash
source "$HOME/.gvm/bin/gvm-init.sh"
gvm install groovy
Note: here, we use GVM to get Groovy. See http://gvmtool.net/

This should take less than a minute (the download of version 2.3.9 is about 32MB). You can check you have groovy installed:
groovy -version
Which should print something like this:

Groovy Version: 2.3.9 JVM: 1.8.0 Vendor: Oracle Corporation OS: Linux

Great, now all you have to do is write some code. And that's the fun part! The code required to get started with Groovy and Spark is ridiculously simple:

@Grab(group = 'com.sparkjava', module = 'spark-core', version = '2.1')
import static spark.Spark.*

get '/hello', { req, res -> 'Hello from Groovy/Raspberry Pi!' }

Enter this code in a file called Server.groovy, then run it:

groovy Server.groovy

Once you see some output from Spark (which does take a little while in the Pi, unfortunately), hit the following URL with your browser (replace the IP address with your Raspberry Pi's IP):

http://192.168.1.18:4567/hello

Notice that, even though Spark was written with Java 8 closures in mind, with the latest versions of Groovy, Groovy closures will also work just fine.

Serving static files is as easy as adding this line to Server.groovy, supposing you want to use the sub-directory public/:
staticFileLocation "public"
If you're fancy serving some dynamic HTML as well, you can write plain Groovy code using the MarkupBuilder class.

Create another file in the same directory as Server.groovy called Page.groovy:

import groovy.xml.MarkupBuilder as Builder

static String createPage(Map queryParams) {
  def writer = new StringWriter()
  new Builder(writer).html {
    h2 'A Dynamic Webpage!'
    div(id: 'query-params') {
      if (!queryParams) li 'No query parameters given'
      else ul {
        for (key in queryParams.keySet()) {
          li "Query param: $key -> ${queryParams[key]}"
        }
      }
    }
    p "Current date: ${new Date()}"
  }
  writer.toString()
}

Now, your complete Server.groovy file should looks like this:


@Grab(group = 'com.sparkjava', module = 'spark-core', version = '2.1')
import static spark.Spark.*

println "Configuring server..."

staticFileLocation "public"

get '/hello', { req, res -> 'Hello from Groovy!' }
get '/page',  { req, res -> Page.createPage(req.queryMap().toMap()) }

Now just run it! Let Groovy know there's more than one Groovy file in the current directory by adding the classpath option as follows:

groovy -cp ./ Server.groovy

And that's it. We've got a hassle-free webserver running in a Raspberry Pi in just a few minutes!


Comments