Course of Raku / Functional, concurrent, reactive, and web programming / Web programming / Cro 101

A Cro route

A Cro HTTP service is described by a set of routes: each route says which URL it handles and what to return. You build them inside a route block with the get keyword:

use Cro::HTTP::Router;
use Cro::HTTP::Server;

my $application = route {
    get -> 'hello' {
        content 'text/plain', 'Hello from Cro!';
    }
}

my $server = Cro::HTTP::Server.new(
    :host('127.0.0.1'),
    :port(8080),
    :application($application),
);
$server.start;

say 'Listening on http://127.0.0.1:8080/hello';

Read the route as “a GET request for the path hello returns the text Hello from Cro!”. The content function sets both the content type and the body — no manual status lines or \r\n in sight. Cro::HTTP::Server ties the routes to an address and port, and .start begins serving.

This example needs Cro installed (zef install cro). Run it, then open http://127.0.0.1:8080/hello.

A route can take URL segments as parameters, return JSON, and much more, but the shape is always this: declare what each path does, hand the routes to a server, and start it. Compared with the raw socket server of the previous section, Cro removes all the protocol bookkeeping and lets you write only the part that is specific to your service.

That is a fitting place to end the course: the high-level, expressive Raku of a Cro route stands on everything that came before — objects, exceptions, regexes and grammars, and the functional, concurrent, and reactive tools of this part.

Course navigation

Quiz — Cro   |   A route with a parameter


💪 Or jump directly to the exercises in this section.