Basic Routing

GreenLightning allows for easy-to-use routing. Routes define how your content is accessed through HTTP.

See the Simple REST Server tutorial for a detailed example on how to create routes.

Creating Routes

Routes need to be defined inside the declareConfiguration method of your GreenApp:

builder.defineRoute()
        .path("/api/hello/${NAME}")
        //.associatedObject("NAME", HelloField.NAME)
        .refineString("NAME", HelloField.NAME, "DefaultName")
        .routeId(HelloStruct.HELLO_WORLD);

HelloField is an enum containing the fields in your application, while HelloMessage is the direct route identifier to be used when registering your listeners and behaviors.

Routes can also be identified by an integer instead of an enum, but this is not recommended for readability reasons.

Routes with JSON

Routes can parse JSON directly, as shown below:

builder.defineRoute()
        .parseJSON()
                .integerField("money", HelloField.MONEY)
                .integerField("age", HelloField.AGE)
                .stringField("name", HelloField.NAME)
        .path("/api/about")
        .routeId(HelloStruct.ABOUT);

This will directly parse JSON from the request's body and associate fields which can be read later (e.g. in your behavior implementing RestListener).

Registering Routes

After you have developed a behavior that should be accessible by a previously defined route, you need to register the behavior inside declareBehavior in GreenApp:

runtime.addRestListener(new HelloBehavior(runtime))
        .includeRoutesByAssoc(HelloStruct.HELLO_WORLD);

Reading Route Fields

Inside a RestListener behavior, you will want to read values from a route. The same syntax can be applied to reading from a JSON body.

@Override
public boolean restRequest(HTTPRequestReader request) {
    StructuredReader record = request.structured();
    name = record.readText(HelloField.NAME);
    ...
    //return false;
}

Route Formatting

Fields inside paths can be formatted in multiple ways:

Route Permutations

You can define multiple paths for routes, and you can add default values if a field could not be found:

builder.defineRoute(HTTPHeaderDefaults.COOKIE)
                       .path("/testpageA?arg=#{myarg}")
                       .path("/testpageA?A=#{myarg}")
                       .refineInteger("myarg", Params.MYARG, 0)
                       .routeId(Routes.EMPTY_EXAMPLE);

In the example above, there are two URLs pointing to the same route: /testpageA?arg=#{myarg} and /testpageA?A=#{myarg} with 0 being the default value of myarg in case it was not specified.

Last updated