12.1. A simple example

Let us get started with a simple example of a web application based on the nice Spark micro-framework.

Spark requires route handlers to extend an abstract base class called spark.Route. The following code snippet does just that:

module sparky

import spark
import spark.Spark

function main = |args| {
  let conf = map[   # (1)
    ["extends", "spark.Route"],   # (2)
    ["implements", map[   # (3)
      ["handle", |this, request, response| {  # (4)
        return "Golo, world!"
      }]
    ]]
  ]
  let fabric = AdapterFabric()  # (5)
  let routeMaker = fabric: maker(conf)  # (6)
  let route = routeMaker: newInstance("/hello")   # (7)
  get(route)  # (8)
}

(1)

An adapter configuration is provided by a map object.

(2)

The extends key allows specifying the name of the parent class (java.lang.Object by default).

(3)

The implements provides a map of method implementations.

(4)

The implementation is given by a closure whose signature matches the parent class definition, and where the first argument is the receiver object that is going to be the adapter instance.

(5)

An adapter fabric provides context for creating adapters. It manages its own class loader.

(6)

An adapter maker creates instances based on a configuration.

(7)

The newInstance() method calls the right constructor based on the parent class constructors and provided argument types.

(8)

The spark.Spark.get() static is method is happy as we feed it a subclass of spark.Route.

Note

Adapter objects implement the gololang.GoloAdapter marker interface, so you can do type checks on them a in: (foo oftype gololang.GoloAdapter.class).