CHAPTER 3ROUTING9

CHAPTER 3Routing

A cgull program says, before it does anything else, which functions handle which requests. This chapter is about how a request finds its handler.

3.1 Routes

A route is a method, a pattern, and a handler. cg_route adds one:

cg_route("GET", "/books/:id", show_book);

and there is a macro for each common method, which is how routes are usually written:

cg_get("/books", list_books);
cg_post("/books", add_book);
cg_get("/books/:id", show_book);
cg_put("/books/:id", replace_book);
cg_patch("/books/:id", update_book);
cg_delete("/books/:id", remove_book);

All routes are added in main before it calls cg_run. When a request comes in, cg_run tries the routes in the order they were added and calls the handler of the first one whose method and pattern both match. Order matters only when two patterns can match the same path; then put the more particular one first:

cg_get("/books/new", new_book_form);  /* first */
cg_get("/books/:id", show_book);      /* also matches "new" */

3.2 Patterns

A pattern is a path, split at its slashes into segments, and it is matched against the request's path one segment at a time. A segment of the pattern matches in one of three ways.

Plain text matches itself exactly, including case. A segment that begins with a colon, like :id, matches any one segment of the path that isn't empty; the handler gets what it matched from cg_param, decoded, so %20 arrives as a space and %2F as a slash that does not split the segment. A * as the last segment matches the rest of the path, slashes and all, and the handler gets it as cg_param(req, "*").

PatternPathResult
//matches
/about/Aboutno match
/books/:id/books/42id is "42"
/books/:id/books/no match: the segment is empty
/books/:id/books/42/no match: one segment too many
/books/:id/books/a%2Fbid is "a/b"
/u/:user/:repo/u/ada/engineuser is "ada", repo is "engine"
/files/*/files/a/b.txt* is "a/b.txt"
/files/*/files/* is ""
/files/*/filesno match

A trailing slash is a segment like any other, so /about and /about/ are different paths. If you want them to be the same, middleware can redirect one to the other; this book does, and Section 3.4 shows how. The query string plays no part in matching.

3.3 Methods

When no route matches both the method and the path, but some route matches the path, the response is 405 Method Not Allowed with an Allow header listing the methods that would have matched. Only when no pattern matches at all is the response a 404.

A GET route also answers HEAD requests. The handler runs as for a GET, and its headers are sent without the body. A route for HEAD itself, added with cg_route("HEAD", ...) before the GET, takes precedence.

cg_any adds a route for every method, which is useful when one handler does its own dispatching:

static void item(cg_req *req, cg_res *res)
{
    const char *m = cg_method(req);

    if (strcmp(m, "GET") == 0)
        show_item(req, res);
    else if (strcmp(m, "DELETE") == 0)
        remove_item(req, res);
    else
        cg_text(res, 405, "no\n");
}

int main(void)
{
    cg_any("/items/:id", item);
    return cg_run();
}

3.4 Middleware

Middleware is a function that sees every request before its handler does. It has the same arguments as a handler, but returns bool: true to let the request carry on, false to stop it there. When it stops a request, the response is whatever it has written, so it should write one. It is added with cg_use:

static bool require_key(cg_req *req, cg_res *res)
{
    const char *key = cg_header(req, "x-api-key");
    const char *want = cg_env("API_KEY");

    if (strncmp(cg_path(req), "/api/", 5) != 0)
        return true;
    if (key != NULL && want != NULL && strcmp(key, want) == 0)
        return true;
    cg_json(res, 401, "{\"error\":\"bad key\"}");
    return false;
}

int main(void)
{
    cg_use(require_key);
    cg_get("/api/books", list_books);
    return cg_run();
}

Middleware functions run in the order they were added, and every one runs for every request, even one that will get a 404 or a 405. The route has already been chosen, so cg_param works. Middleware can also prepare the response rather than stop it: this book's own middleware sets a Cache-Control header on every page, and sends paths ending in a slash elsewhere:

static bool tidy(cg_req *req, cg_res *res)
{
    const char *path = cg_path(req);
    size_t len = strlen(path);

    if (len > 1 && path[len - 1] == '/') {
        cg_redirect(res, 301, cg_sprintf("%.*s", (int)(len - 1), path));
        return false;
    }
    cg_set_header(res, "Cache-Control", "public, max-age=300");
    return true;
}

3.5 Not Found

The default 404 page is a line of plain text. To have your own, pass a handler to cg_not_found:

static void not_found(cg_req *req, cg_res *res)
{
    cg_html(res, 404, cg_sprintf("<h1>No page at %s</h1>",
                                 cg_esc(cg_path(req))));
}

int main(void)
{
    cg_get("/", home);
    cg_not_found(not_found);
    return cg_run();
}

A handler may also decide for itself that there is nothing there. If /books/:id is asked for a book that doesn't exist, it can call the same function. That is what this book does when asked for a chapter it doesn't have; try Chapter 13.

Exercise 3-1. Write a route that serves /files/* and answers with the number of segments in the rest of the path.

Exercise 3-2. Write middleware that logs every request's method and path with cg_log, and lets it carry on.

Set in Tinos and Courier Prime. Served by a C program on Cloudflare Workers, cgull 0.1.0. Source on GitHub, BSD licensed.