A simple Kotlin API server with Jetty

Jan 29, 2018

Okay, so the first thing I’ll need to build if I want to create a Certificate Authority server is a simple API response to HTTP calls. The example I’ve written below uses Jetty, because it’s light-weight.

I’m using IntelliJ as my IDE, with Maven as my package manager. Let’s start by writing the code to start up a server:

import mu.KLogging
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.ServletHolder
import org.eclipse.jetty.webapp.WebAppContext

class API {

    companion object: KLogging()

    fun start() {
        val handler = createHandler()
        Server(8080).apply {
            setHandler(handler)
            start()
        }
        logger.info("Started server on port 8080")
    }

    private fun createHandler(): WebAppContext {
        return WebAppContext().apply {
            setResourceBase("/")
            addServlet(ServletHolder(Status()), "/message/\*")
        }
    }

}

There’s quite a bit to explain in here. Let’s start by looking at syntax.

Syntax

If you’re coming from a Java background, then the first thing you’ll notice is the lack of semicolons. There’s nothing to stop you putting them in, but your IDE will likely remind you that they’re superfluous. Notice also that functions are declared with the fun keyword.

KLogging

Companion Objects

Companion objects are often touted as Kotlin’s alternative to static methods, but it goes a bit deeper than that.

The “.apply” method

Starting the Server

Now it’s all very well that we have a class set up to initialise our server, but we need to call that class. In Java, we’d normally instantiate the class, and then call a method, but we can do all of that in one expression in Kotlin, by again using the apply keyword.

fun main(args: Array<String>) {
    API().apply {
        start()
    }
}

Notice that the main method has the same parameters as its counterpart in Java (ie. An array of argument strings). The apply keyword here is used to instantiate our server class, and then run the start method.