CHAPTER 5RESPONSES15

CHAPTER 5Responses

A response is built up in res while the handler runs: first, usually, the status and headers, then the body. Nothing is sent until the handler returns, so the order in which they are set doesn't matter: a handler that has written half a page can still change the status or add a header.

5.1 Status and Headers

The status starts at 200. cg_status changes it:

cg_status(res, 201);

cg_set_header sets a header, replacing any earlier one of the same name, and cg_add_header adds one, keeping the others, for the few headers that can appear more than once:

cg_set_header(res, "Content-Type", "text/csv");
cg_set_header(res, "Cache-Control", "no-store");
cg_add_header(res, "Link", "</style.css>; rel=preload; as=style");

If no Content-Type is set, the response is sent as text/html; charset=utf-8. A carriage return or newline in a header's name or value is replaced by a space, so a value taken from the request can't add headers of its own.

5.2 Writing the Body

Three functions append to the body. cg_write appends bytes, cg_puts a string, and cg_printf formatted text:

cg_puts(res, "<ul>");
for (int i = 0; i < n; i++)
    cg_printf(res, "<li>%s: %d</li>", cg_esc(names[i]), scores[i]);
cg_puts(res, "</ul>");

cg_printf has the conversions of printf, and the compiler checks its arguments in the same way. It escapes nothing: text from the visitor, or from anywhere you don't control, goes through cg_esc first. cg_vprintf takes a va_list, for functions of your own that format in the same way.

The body is kept in memory until the handler returns, and grows as needed. A response of a few megabytes is no trouble; one that would fill the Worker's memory (Section 6.5) is.

5.3 Shortcuts

Most responses are a status, a type and a body, and three functions set all three at once:

cg_text(res, 200, "plain text\n");
cg_html(res, 200, "<p>HTML</p>");
cg_json(res, 200, "{\"ok\":true}");

Each sets the status and replaces the Content-Type, then appends its string, which may be NULL to append nothing. The body can be continued afterwards with cg_printf. JSON is built with cg_sprintf and cg_json_str, which quotes and escapes a string:

cg_json(res, 200, cg_sprintf("{\"name\":%s,\"count\":%d}",
                             cg_json_str(name), count));

5.4 Redirects

cg_redirect sets the status and the Location header:

cg_redirect(res, 303, "/thanks");

Use 303 after a form post, so the browser follows with a GET; 301 or 308 for a page that has moved for good; 302 or 307 for one that has moved for now. A redirect needs no body.

5.5 Cookies

cg_set_cookie adds a Set-Cookie header. The fourth argument holds the cookie's attributes, as they appear in the header, or NULL:

cg_set_cookie(res, "theme", "dark", "Path=/; Max-Age=31536000; SameSite=Lax");
cg_set_cookie(res, "session", token, "Path=/; HttpOnly; Secure");

Each call adds another cookie. The value is not encoded; if it might contain a semicolon, a comma, or a space, pass it through cg_url_encode, and cg_cookie will decode it when it comes back. To delete a cookie, set it again with Max-Age=0.

5.6 When Things Go Wrong

A handler that finds the request wanting sends a 4xx status itself, with whatever explanation helps. When the program itself fails, cgull sends 500 Internal Server Error and writes the reason in the Worker's logs. That happens when the program:

Only that request fails; the next starts afresh. A response that has been partly built is not sent. To fail on purpose, with a message in the logs, call cg_log and then exit(1).

Exercise 5-1. Write a handler that serves a CSV file of the numbers 1 to 100 and their squares, with a Content-Disposition header that makes the browser download it as squares.csv.

Exercise 5-2. Count a visitor's visits in a cookie, and show the count on the page.

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