CHAPTER 1A Tutorial Introduction
Let us begin with a quick introduction to cgull. Our aim is to show the essential parts of a real program without getting bogged down in details; those come in later chapters. By the end of this one you will have a Worker on the internet, written in C.
1.1 Getting Started
You need Node.js 20 or later, and a Cloudflare account for deploying.
You do not need a C compiler for WebAssembly: the first time you build,
cgull downloads wasi-sdk, a Clang set up for WebAssembly, into
~/.cache/wasi-sdk. It is about 120 MB and is downloaded once.
Make a project with cgull new:
$ npx cgull new hello $ cd hello $ npm install
cgull is not yet on npm. Until it is, clone its repository
and run the command from there, as node ~/cgull/bin/cgull.js new
hello; the new project's package.json points back at
that checkout.
The project has a few files. src/main.c is the program.
public/ holds static files, such as a stylesheet, that are
served without involving the program. wrangler.jsonc is the
Worker's configuration, and package.json lists cgull and
wrangler, Cloudflare's command for running and deploying Workers.
1.2 The First Program
The first program to write is the same in every language. Replace
src/main.c with this:
#include <cgull.h>
static void hello(cg_req *req, cg_res *res)
{
cg_puts(res, "hello, world\n");
}
int main(void)
{
cg_get("/", hello);
return cg_run();
}
Now for some explanation. A cgull program starts at
main, like any C program. This one does two things. It calls
cg_get to say that a GET request for the path
/ should be handled by the function hello. Then
it calls cg_run, which reads the request, finds the route that
matches it, calls the handler, and sends the response.
A handler is a function that takes two arguments: req, the
request, and res, the response being built. Both are pointers
to types that <cgull.h> keeps opaque; you use them only
through the library's functions. hello ignores the request
and appends a line to the response's body with cg_puts.
Nothing is sent while the handler runs. When it returns,
cg_run sends the status (200 unless you say otherwise), the
headers, and the body together.
1.3 Running It
The quickest way to try a program is cgull run, which
builds it, sends it one request, and prints the response:
$ npx cgull run / hello, world $ npx cgull run -i / HTTP 200 OK content-type: text/html; charset=utf-8 hello, world
With -i it prints the status and headers as well. The
content type is HTML because that is the default; we will see how to change
it. A path with no route gets a 404:
$ npx cgull run -i /nowhere HTTP 404 Not Found content-type: text/plain; charset=utf-8 Not found: /nowhere
To use a browser, start the development server:
$ npm run dev
It serves the Worker at http://localhost:8787, on the same
runtime Cloudflare uses, and rebuilds the program whenever a file in
src/ changes.
1.4 Parameters
A route's pattern can have parts that match anything. A segment
written :name matches one segment of the path, and the handler
reads what it matched with cg_param:
static void greet(cg_req *req, cg_res *res)
{
const char *name = cg_param(req, "name");
cg_printf(res, "<h1>Hello, %s!</h1>", cg_esc(name));
}
int main(void)
{
cg_get("/", hello);
cg_get("/hello/:name", greet);
return cg_run();
}
$ npx cgull run /hello/Ada%20Lovelace <h1>Hello, Ada Lovelace!</h1>
cg_printf is printf for the response body. The
name comes from the visitor, so before it goes into the page it passes
through cg_esc, which escapes the characters that mean
something in HTML. Without it, a visitor could put a script in the URL and
have the page run it. Anything from the request that ends up in HTML should
go through cg_esc.
Notice what the program doesn't do: it doesn't free the string
cg_esc returned. Memory in cgull lasts until the request
ends, and then all of it goes at once. Chapter 6 has the details.
The query string is read the same way, with cg_query. For
/search?q=c+programming, cg_query(req, "q") is
"c programming". A parameter that isn't there gives
NULL, which cg_esc treats as an empty string.
1.5 Forms
Here is a page with a form, and a handler for what it posts:
static void form(cg_req *req, cg_res *res)
{
cg_puts(res, "<form method=post action=/greet>"
"<input name=name> <button>Greet me</button>"
"</form>");
}
static void greet_post(cg_req *req, cg_res *res)
{
const char *name = cg_form(req, "name");
if (name == NULL || *name == '\0') {
cg_redirect(res, 303, "/form");
return;
}
cg_redirect(res, 303, cg_sprintf("/hello/%s", cg_url_encode(name)));
}
int main(void)
{
cg_get("/", hello);
cg_get("/hello/:name", greet);
cg_get("/form", form);
cg_post("/greet", greet_post);
return cg_run();
}
cg_post adds a route for POST requests, and
cg_form reads a field of the form. The handler answers with a
redirect: status 303 tells the browser to load the new location with a
GET, so reloading the page doesn't post the form again.
cg_sprintf builds the location, and cg_url_encode
makes the name safe to put in a path.
$ npx cgull run -i -d name=Grace /greet HTTP 303 See Other content-type: text/html; charset=utf-8 location: /hello/Grace
Given -d, cgull run sends a POST with that
body, as a browser's form would.
1.6 Deploying
When the Worker does what you want, deploy it:
$ npm run deploy
The first time, wrangler asks you to log in to Cloudflare. Then it
builds the program, uploads it, and prints the Worker's address, something
like https://hello.your-name.workers.dev. The name comes from
wrangler.jsonc. Each deploy replaces the last within a few
seconds.
That is all there is to it. The rest of this book fills in the details: the other ways to route a request, what else can be read from one, what can be sent back, and how it works underneath.
Exercise 1-1. Change hello to answer in plain text, using
cg_text instead of cg_puts. Check the
content-type with cgull run -i.
Exercise 1-2. Add a route /add/:a/:b that answers with the
sum of two numbers. What should it do with /add/1/x?
Exercise 1-3. Make greet answer with JSON when the request
has ?format=json. Use cg_json and
cg_json_str.