create-cgull 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,529 @@
1
+ // The cgull runtime: CGI in, router, CGI out. See cgull.h.
2
+ //
3
+ // Nothing is freed. A program handles one request and exits, and on
4
+ // Workers the whole instance is thrown away afterwards.
5
+
6
+ #include "cgull.h"
7
+
8
+ #include <ctype.h>
9
+ #include <stdio.h>
10
+ #include <stdlib.h>
11
+ #include <string.h>
12
+ #include <strings.h>
13
+
14
+ typedef struct {
15
+ char *name;
16
+ char *value;
17
+ } pair;
18
+
19
+ typedef struct {
20
+ pair *items;
21
+ size_t len, cap;
22
+ } pairs;
23
+
24
+ struct cg_req {
25
+ const char *method;
26
+ const char *raw_path; // as sent, still percent-encoded
27
+ bool path_encoded; // false if we only had the decoded PATH_INFO
28
+ char *path;
29
+ pairs params;
30
+ pairs query;
31
+ pairs cookies;
32
+ pairs form;
33
+ bool cookies_parsed, form_parsed, body_read;
34
+ char *body;
35
+ size_t body_len;
36
+ };
37
+
38
+ struct cg_res {
39
+ int status;
40
+ pairs headers;
41
+ char *buf;
42
+ size_t len, cap;
43
+ };
44
+
45
+ typedef struct {
46
+ const char *method;
47
+ const char *pattern;
48
+ cg_handler handler;
49
+ } route;
50
+
51
+ static route *routes;
52
+ static size_t routes_len, routes_cap;
53
+ static cg_middleware *middleware;
54
+ static size_t middleware_len, middleware_cap;
55
+ static cg_handler not_found_handler;
56
+
57
+ static void *xrealloc(void *p, size_t size) {
58
+ p = realloc(p, size);
59
+ if (!p) {
60
+ fputs("cgull: out of memory\n", stderr);
61
+ abort();
62
+ }
63
+ return p;
64
+ }
65
+
66
+ #define GROW(arr, len, cap) \
67
+ do { \
68
+ if ((len) == (cap)) { \
69
+ (cap) = (cap) ? (cap) * 2 : 8; \
70
+ (arr) = xrealloc((arr), (cap) * sizeof *(arr)); \
71
+ } \
72
+ } while (0)
73
+
74
+ static char *xstrndup(const char *s, size_t n) {
75
+ char *d = xrealloc(NULL, n + 1);
76
+ memcpy(d, s, n);
77
+ d[n] = 0;
78
+ return d;
79
+ }
80
+
81
+ static void pairs_add(pairs *p, char *name, char *value) {
82
+ GROW(p->items, p->len, p->cap);
83
+ p->items[p->len++] = (pair){name, value};
84
+ }
85
+
86
+ static const char *pairs_get(const pairs *p, const char *name) {
87
+ for (size_t i = 0; i < p->len; i++)
88
+ if (strcmp(p->items[i].name, name) == 0) return p->items[i].value;
89
+ return NULL;
90
+ }
91
+
92
+ static int hexval(int c) {
93
+ if (c >= '0' && c <= '9') return c - '0';
94
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
95
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
96
+ return -1;
97
+ }
98
+
99
+ // Percent-decodes n bytes of s into a new string. In query strings and
100
+ // forms '+' means a space; in paths it doesn't.
101
+ static char *decode(const char *s, size_t n, bool plus_is_space) {
102
+ char *out = xrealloc(NULL, n + 1), *o = out;
103
+ for (size_t i = 0; i < n; i++) {
104
+ int hi, lo;
105
+ if (s[i] == '+' && plus_is_space) {
106
+ *o++ = ' ';
107
+ } else if (s[i] == '%' && i + 2 < n && (hi = hexval(s[i + 1])) >= 0 &&
108
+ (lo = hexval(s[i + 2])) >= 0) {
109
+ *o++ = (char)(hi * 16 + lo);
110
+ i += 2;
111
+ } else {
112
+ *o++ = s[i];
113
+ }
114
+ }
115
+ *o = 0;
116
+ return out;
117
+ }
118
+
119
+ // Splits "a=1&b=2" (or "a=1; b=2" for cookies) into decoded pairs.
120
+ static void parse_pairs(pairs *out, const char *s, char sep, bool plus_is_space) {
121
+ while (s && *s) {
122
+ while (*s == ' ' || *s == '\t') s++;
123
+ const char *end = strchr(s, sep);
124
+ size_t len = end ? (size_t)(end - s) : strlen(s);
125
+ if (len) {
126
+ const char *eq = memchr(s, '=', len);
127
+ size_t nlen = eq ? (size_t)(eq - s) : len;
128
+ const char *v = eq ? eq + 1 : s + len;
129
+ size_t vlen = (size_t)(s + len - v);
130
+ pairs_add(out, decode(s, nlen, plus_is_space), decode(v, vlen, plus_is_space));
131
+ }
132
+ s = end ? end + 1 : NULL;
133
+ }
134
+ }
135
+
136
+ // --- Routing ---------------------------------------------------------------
137
+
138
+ void cg_route(const char *method, const char *pattern, cg_handler handler) {
139
+ GROW(routes, routes_len, routes_cap);
140
+ routes[routes_len++] = (route){method, pattern, handler};
141
+ }
142
+
143
+ void cg_use(cg_middleware fn) {
144
+ GROW(middleware, middleware_len, middleware_cap);
145
+ middleware[middleware_len++] = fn;
146
+ }
147
+
148
+ void cg_not_found(cg_handler handler) {
149
+ not_found_handler = handler;
150
+ }
151
+
152
+ // Matches path against pattern, adding any :params to req->params.
153
+ static bool match(cg_req *req, const char *pattern, const char *path) {
154
+ if (*pattern != '/' || *path != '/') return false;
155
+ const char *p = pattern + 1, *s = path + 1;
156
+ for (;;) {
157
+ const char *pe = strchr(p, '/'), *se = strchr(s, '/');
158
+ if (!pe) pe = p + strlen(p);
159
+ if (!se) se = s + strlen(s);
160
+ size_t plen = (size_t)(pe - p), slen = (size_t)(se - s);
161
+
162
+ if (plen == 1 && *p == '*' && !*pe) {
163
+ size_t rest = strlen(s);
164
+ pairs_add(&req->params, xstrndup("*", 1),
165
+ req->path_encoded ? decode(s, rest, false) : xstrndup(s, rest));
166
+ return true;
167
+ }
168
+ if (*p == ':') {
169
+ if (!slen) return false;
170
+ pairs_add(&req->params, xstrndup(p + 1, plen - 1),
171
+ req->path_encoded ? decode(s, slen, false) : xstrndup(s, slen));
172
+ } else if (plen != slen || memcmp(p, s, plen) != 0) {
173
+ return false;
174
+ }
175
+ if (!*pe || !*se) return !*pe && !*se;
176
+ p = pe + 1;
177
+ s = se + 1;
178
+ }
179
+ }
180
+
181
+ static bool method_matches(const char *route_method, const char *method) {
182
+ return strcmp(route_method, "*") == 0 || strcmp(route_method, method) == 0 ||
183
+ (strcmp(method, "HEAD") == 0 && strcmp(route_method, "GET") == 0);
184
+ }
185
+
186
+ // --- Request ---------------------------------------------------------------
187
+
188
+ const char *cg_method(cg_req *req) { return req->method; }
189
+ const char *cg_path(cg_req *req) { return req->path; }
190
+ const char *cg_param(cg_req *req, const char *name) { return pairs_get(&req->params, name); }
191
+ const char *cg_query(cg_req *req, const char *name) { return pairs_get(&req->query, name); }
192
+
193
+ const char *cg_env(const char *name) {
194
+ return getenv(name);
195
+ }
196
+
197
+ const char *cg_header(cg_req *req, const char *name) {
198
+ (void)req;
199
+ if (strcasecmp(name, "content-type") == 0) return getenv("CONTENT_TYPE");
200
+ if (strcasecmp(name, "content-length") == 0) return getenv("CONTENT_LENGTH");
201
+ size_t n = strlen(name);
202
+ char *key = xrealloc(NULL, n + 6);
203
+ memcpy(key, "HTTP_", 5);
204
+ for (size_t i = 0; i < n; i++)
205
+ key[5 + i] = name[i] == '-' ? '_' : (char)toupper((unsigned char)name[i]);
206
+ key[5 + n] = 0;
207
+ return getenv(key);
208
+ }
209
+
210
+ const char *cg_cookie(cg_req *req, const char *name) {
211
+ if (!req->cookies_parsed) {
212
+ parse_pairs(&req->cookies, getenv("HTTP_COOKIE"), ';', false);
213
+ req->cookies_parsed = true;
214
+ }
215
+ return pairs_get(&req->cookies, name);
216
+ }
217
+
218
+ const char *cg_body(cg_req *req, size_t *len) {
219
+ if (!req->body_read) {
220
+ req->body_read = true;
221
+ const char *cl = getenv("CONTENT_LENGTH");
222
+ size_t want = cl ? strtoull(cl, NULL, 10) : 0;
223
+ req->body = xrealloc(NULL, want + 1);
224
+ while (req->body_len < want) {
225
+ size_t n = fread(req->body + req->body_len, 1, want - req->body_len, stdin);
226
+ if (!n) break;
227
+ req->body_len += n;
228
+ }
229
+ req->body[req->body_len] = 0;
230
+ }
231
+ if (len) *len = req->body_len;
232
+ return req->body;
233
+ }
234
+
235
+ const char *cg_form(cg_req *req, const char *name) {
236
+ if (!req->form_parsed) {
237
+ req->form_parsed = true;
238
+ const char *type = getenv("CONTENT_TYPE");
239
+ const char *form = "application/x-www-form-urlencoded";
240
+ if (type && strncasecmp(type, form, strlen(form)) == 0)
241
+ parse_pairs(&req->form, cg_body(req, NULL), '&', true);
242
+ }
243
+ return pairs_get(&req->form, name);
244
+ }
245
+
246
+ // --- Response --------------------------------------------------------------
247
+
248
+ void cg_status(cg_res *res, int status) {
249
+ res->status = status;
250
+ }
251
+
252
+ // CR or LF in a header would let a value start a header of its own.
253
+ static char *header_safe(const char *s) {
254
+ char *d = xstrndup(s, strlen(s));
255
+ for (char *c = d; *c; c++)
256
+ if (*c == '\r' || *c == '\n') *c = ' ';
257
+ return d;
258
+ }
259
+
260
+ void cg_add_header(cg_res *res, const char *name, const char *value) {
261
+ pairs_add(&res->headers, header_safe(name), header_safe(value ? value : ""));
262
+ }
263
+
264
+ void cg_set_header(cg_res *res, const char *name, const char *value) {
265
+ size_t kept = 0;
266
+ for (size_t i = 0; i < res->headers.len; i++)
267
+ if (strcasecmp(res->headers.items[i].name, name) != 0)
268
+ res->headers.items[kept++] = res->headers.items[i];
269
+ res->headers.len = kept;
270
+ cg_add_header(res, name, value);
271
+ }
272
+
273
+ void cg_set_cookie(cg_res *res, const char *name, const char *value, const char *attrs) {
274
+ cg_add_header(res, "Set-Cookie",
275
+ attrs && *attrs ? cg_sprintf("%s=%s; %s", name, value, attrs)
276
+ : cg_sprintf("%s=%s", name, value));
277
+ }
278
+
279
+ void cg_write(cg_res *res, const void *data, size_t len) {
280
+ if (res->len + len > res->cap) {
281
+ while (res->len + len > res->cap) res->cap = res->cap ? res->cap * 2 : 4096;
282
+ res->buf = xrealloc(res->buf, res->cap);
283
+ }
284
+ memcpy(res->buf + res->len, data, len);
285
+ res->len += len;
286
+ }
287
+
288
+ void cg_puts(cg_res *res, const char *s) {
289
+ cg_write(res, s, strlen(s));
290
+ }
291
+
292
+ void cg_vprintf(cg_res *res, const char *fmt, va_list ap) {
293
+ va_list ap2;
294
+ va_copy(ap2, ap);
295
+ int n = vsnprintf(NULL, 0, fmt, ap2);
296
+ va_end(ap2);
297
+ if (n <= 0) return;
298
+ if (res->len + (size_t)n + 1 > res->cap) {
299
+ while (res->len + (size_t)n + 1 > res->cap) res->cap = res->cap ? res->cap * 2 : 4096;
300
+ res->buf = xrealloc(res->buf, res->cap);
301
+ }
302
+ vsnprintf(res->buf + res->len, (size_t)n + 1, fmt, ap);
303
+ res->len += (size_t)n;
304
+ }
305
+
306
+ void cg_printf(cg_res *res, const char *fmt, ...) {
307
+ va_list ap;
308
+ va_start(ap, fmt);
309
+ cg_vprintf(res, fmt, ap);
310
+ va_end(ap);
311
+ }
312
+
313
+ static void respond(cg_res *res, int status, const char *type, const char *s) {
314
+ cg_status(res, status);
315
+ cg_set_header(res, "Content-Type", type);
316
+ if (s) cg_puts(res, s);
317
+ }
318
+
319
+ void cg_text(cg_res *res, int status, const char *s) {
320
+ respond(res, status, "text/plain; charset=utf-8", s);
321
+ }
322
+
323
+ void cg_html(cg_res *res, int status, const char *s) {
324
+ respond(res, status, "text/html; charset=utf-8", s);
325
+ }
326
+
327
+ void cg_json(cg_res *res, int status, const char *json) {
328
+ respond(res, status, "application/json", json);
329
+ }
330
+
331
+ void cg_redirect(cg_res *res, int status, const char *location) {
332
+ cg_status(res, status);
333
+ cg_set_header(res, "Location", location);
334
+ }
335
+
336
+ // --- Strings ---------------------------------------------------------------
337
+
338
+ typedef struct {
339
+ char *s;
340
+ size_t len, cap;
341
+ } strbuf;
342
+
343
+ static void sb_add(strbuf *b, const char *s, size_t n) {
344
+ if (b->len + n + 1 > b->cap) {
345
+ while (b->len + n + 1 > b->cap) b->cap = b->cap ? b->cap * 2 : 64;
346
+ b->s = xrealloc(b->s, b->cap);
347
+ }
348
+ memcpy(b->s + b->len, s, n);
349
+ b->len += n;
350
+ b->s[b->len] = 0;
351
+ }
352
+
353
+ char *cg_esc(const char *s) {
354
+ strbuf b = {0};
355
+ sb_add(&b, "", 0);
356
+ for (; s && *s; s++) {
357
+ switch (*s) {
358
+ case '&': sb_add(&b, "&amp;", 5); break;
359
+ case '<': sb_add(&b, "&lt;", 4); break;
360
+ case '>': sb_add(&b, "&gt;", 4); break;
361
+ case '"': sb_add(&b, "&quot;", 6); break;
362
+ case '\'': sb_add(&b, "&#39;", 5); break;
363
+ default: sb_add(&b, s, 1);
364
+ }
365
+ }
366
+ return b.s;
367
+ }
368
+
369
+ char *cg_json_str(const char *s) {
370
+ strbuf b = {0};
371
+ sb_add(&b, "\"", 1);
372
+ for (; s && *s; s++) {
373
+ unsigned char c = (unsigned char)*s;
374
+ char esc[8];
375
+ switch (c) {
376
+ case '"': sb_add(&b, "\\\"", 2); break;
377
+ case '\\': sb_add(&b, "\\\\", 2); break;
378
+ case '\n': sb_add(&b, "\\n", 2); break;
379
+ case '\r': sb_add(&b, "\\r", 2); break;
380
+ case '\t': sb_add(&b, "\\t", 2); break;
381
+ default:
382
+ if (c < 0x20) {
383
+ snprintf(esc, sizeof esc, "\\u%04x", c);
384
+ sb_add(&b, esc, 6);
385
+ } else {
386
+ sb_add(&b, s, 1);
387
+ }
388
+ }
389
+ }
390
+ sb_add(&b, "\"", 1);
391
+ return b.s;
392
+ }
393
+
394
+ char *cg_url_encode(const char *s) {
395
+ static const char hex[] = "0123456789ABCDEF";
396
+ strbuf b = {0};
397
+ sb_add(&b, "", 0);
398
+ for (; s && *s; s++) {
399
+ unsigned char c = (unsigned char)*s;
400
+ if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
401
+ sb_add(&b, s, 1);
402
+ } else {
403
+ char enc[3] = {'%', hex[c >> 4], hex[c & 15]};
404
+ sb_add(&b, enc, 3);
405
+ }
406
+ }
407
+ return b.s;
408
+ }
409
+
410
+ char *cg_sprintf(const char *fmt, ...) {
411
+ va_list ap;
412
+ va_start(ap, fmt);
413
+ int n = vsnprintf(NULL, 0, fmt, ap);
414
+ va_end(ap);
415
+ char *s = xrealloc(NULL, n > 0 ? (size_t)n + 1 : 1);
416
+ va_start(ap, fmt);
417
+ vsnprintf(s, n > 0 ? (size_t)n + 1 : 1, fmt, ap);
418
+ va_end(ap);
419
+ return s;
420
+ }
421
+
422
+ void cg_log(const char *fmt, ...) {
423
+ va_list ap;
424
+ va_start(ap, fmt);
425
+ vfprintf(stderr, fmt, ap);
426
+ va_end(ap);
427
+ fputc('\n', stderr);
428
+ }
429
+
430
+ // --- Running ---------------------------------------------------------------
431
+
432
+ static const char *reason(int status) {
433
+ switch (status) {
434
+ case 200: return "OK";
435
+ case 201: return "Created";
436
+ case 204: return "No Content";
437
+ case 301: return "Moved Permanently";
438
+ case 302: return "Found";
439
+ case 303: return "See Other";
440
+ case 304: return "Not Modified";
441
+ case 307: return "Temporary Redirect";
442
+ case 308: return "Permanent Redirect";
443
+ case 400: return "Bad Request";
444
+ case 401: return "Unauthorized";
445
+ case 403: return "Forbidden";
446
+ case 404: return "Not Found";
447
+ case 405: return "Method Not Allowed";
448
+ case 409: return "Conflict";
449
+ case 422: return "Unprocessable Content";
450
+ case 429: return "Too Many Requests";
451
+ case 500: return "Internal Server Error";
452
+ case 503: return "Service Unavailable";
453
+ default: return "";
454
+ }
455
+ }
456
+
457
+ static void read_request(cg_req *req) {
458
+ const char *method = getenv("REQUEST_METHOD");
459
+ req->method = method && *method ? method : "GET";
460
+
461
+ // REQUEST_URI keeps the path encoded, so "/a%2Fb" stays one segment.
462
+ // Plain CGI servers may only give us the decoded PATH_INFO.
463
+ const char *uri = getenv("REQUEST_URI");
464
+ if (uri && *uri == '/') {
465
+ const char *q = strchr(uri, '?');
466
+ req->raw_path = q ? xstrndup(uri, (size_t)(q - uri)) : uri;
467
+ req->path_encoded = true;
468
+ req->path = decode(req->raw_path, strlen(req->raw_path), false);
469
+ } else {
470
+ const char *info = getenv("PATH_INFO");
471
+ req->raw_path = info && *info ? info : "/";
472
+ req->path = xstrndup(req->raw_path, strlen(req->raw_path));
473
+ }
474
+ parse_pairs(&req->query, getenv("QUERY_STRING"), '&', true);
475
+ }
476
+
477
+ static void default_not_found(cg_req *req, cg_res *res) {
478
+ cg_text(res, 404, cg_sprintf("Not found: %s\n", req->path));
479
+ }
480
+
481
+ static void write_response(cg_req *req, cg_res *res) {
482
+ printf("Status: %d %s\r\n", res->status, reason(res->status));
483
+ bool typed = false;
484
+ for (size_t i = 0; i < res->headers.len; i++) {
485
+ pair *h = &res->headers.items[i];
486
+ if (strcasecmp(h->name, "content-type") == 0) typed = true;
487
+ printf("%s: %s\r\n", h->name, h->value);
488
+ }
489
+ if (!typed) printf("Content-Type: text/html; charset=utf-8\r\n");
490
+ printf("\r\n");
491
+ if (strcmp(req->method, "HEAD") != 0) fwrite(res->buf, 1, res->len, stdout);
492
+ fflush(stdout);
493
+ }
494
+
495
+ int cg_run(void) {
496
+ static cg_req req;
497
+ static cg_res res = {.status = 200};
498
+ read_request(&req);
499
+
500
+ cg_handler handler = NULL;
501
+ strbuf allow = {0};
502
+ for (size_t i = 0; i < routes_len && !handler; i++) {
503
+ req.params.len = 0;
504
+ if (!match(&req, routes[i].pattern, req.raw_path)) continue;
505
+ if (method_matches(routes[i].method, req.method)) {
506
+ handler = routes[i].handler;
507
+ } else {
508
+ if (allow.len) sb_add(&allow, ", ", 2);
509
+ sb_add(&allow, routes[i].method, strlen(routes[i].method));
510
+ }
511
+ }
512
+ if (!handler) req.params.len = 0;
513
+
514
+ for (size_t i = 0; i < middleware_len; i++)
515
+ if (!middleware[i](&req, &res)) goto done;
516
+
517
+ if (handler) {
518
+ handler(&req, &res);
519
+ } else if (allow.len) {
520
+ cg_set_header(&res, "Allow", allow.s);
521
+ cg_text(&res, 405, "Method not allowed\n");
522
+ } else {
523
+ res.status = 404;
524
+ (not_found_handler ? not_found_handler : default_not_found)(&req, &res);
525
+ }
526
+ done:
527
+ write_response(&req, &res);
528
+ return 0;
529
+ }
@@ -0,0 +1,120 @@
1
+ // cgull: write Cloudflare Workers in C.
2
+ //
3
+ // A cgull program registers routes and calls cg_run():
4
+ //
5
+ // static void hello(cg_req *req, cg_res *res) {
6
+ // cg_printf(res, "<h1>Hello, %s!</h1>", cg_esc(cg_param(req, "name")));
7
+ // }
8
+ //
9
+ // int main(void) {
10
+ // cg_get("/hello/:name", hello);
11
+ // return cg_run();
12
+ // }
13
+ //
14
+ // Every request runs in a fresh instance of the program, so memory never
15
+ // outlives a request. Allocate freely and don't bother freeing: strings
16
+ // returned by cg_* functions stay valid until the request ends.
17
+ //
18
+ // Under the hood a cgull program is a CGI program (request in environment
19
+ // variables and stdin, response on stdout), so it also builds natively and
20
+ // runs under any CGI server.
21
+
22
+ #ifndef CGULL_H
23
+ #define CGULL_H
24
+
25
+ #include <stdarg.h>
26
+ #include <stdbool.h>
27
+ #include <stddef.h>
28
+
29
+ // The cgull version as a string, e.g. "0.1.0". `cgull build` defines it.
30
+ #ifndef CGULL_VERSION
31
+ #define CGULL_VERSION "unknown"
32
+ #endif
33
+
34
+ typedef struct cg_req cg_req;
35
+ typedef struct cg_res cg_res;
36
+ typedef void (*cg_handler)(cg_req *req, cg_res *res);
37
+
38
+ // --- Routing ---------------------------------------------------------------
39
+ //
40
+ // Patterns match the path segment by segment. ":name" matches one segment
41
+ // and is read with cg_param(req, "name"); a final "*" matches the rest of
42
+ // the path (possibly empty), read with cg_param(req, "*"). Routes are tried
43
+ // in the order they were added. A HEAD request uses the GET route.
44
+
45
+ void cg_route(const char *method, const char *pattern, cg_handler handler);
46
+ #define cg_get(pattern, handler) cg_route("GET", pattern, handler)
47
+ #define cg_post(pattern, handler) cg_route("POST", pattern, handler)
48
+ #define cg_put(pattern, handler) cg_route("PUT", pattern, handler)
49
+ #define cg_patch(pattern, handler) cg_route("PATCH", pattern, handler)
50
+ #define cg_delete(pattern, handler) cg_route("DELETE", pattern, handler)
51
+ #define cg_any(pattern, handler) cg_route("*", pattern, handler)
52
+
53
+ // Runs before the route's handler. Return false to stop there (after
54
+ // writing a response, say a 401).
55
+ typedef bool (*cg_middleware)(cg_req *req, cg_res *res);
56
+ void cg_use(cg_middleware middleware);
57
+
58
+ // Replaces the default 404 page. The status is already 404 when it runs.
59
+ void cg_not_found(cg_handler handler);
60
+
61
+ // Reads the request, dispatches it and writes the response. Return its
62
+ // result from main().
63
+ int cg_run(void);
64
+
65
+ // --- Request ---------------------------------------------------------------
66
+ //
67
+ // Lookups return NULL when the thing is missing. Names are case-sensitive,
68
+ // except for headers.
69
+
70
+ const char *cg_method(cg_req *req);
71
+ const char *cg_path(cg_req *req); // decoded, without the query string
72
+ const char *cg_param(cg_req *req, const char *name);
73
+ const char *cg_query(cg_req *req, const char *name);
74
+ const char *cg_header(cg_req *req, const char *name);
75
+ const char *cg_cookie(cg_req *req, const char *name);
76
+ // A field of an application/x-www-form-urlencoded body.
77
+ const char *cg_form(cg_req *req, const char *name);
78
+ // The raw body, NUL-terminated. len may be NULL.
79
+ const char *cg_body(cg_req *req, size_t *len);
80
+
81
+ // A Worker variable or secret (from wrangler.jsonc "vars" or
82
+ // `wrangler secret put`), or NULL.
83
+ const char *cg_env(const char *name);
84
+
85
+ // --- Response --------------------------------------------------------------
86
+ //
87
+ // The status defaults to 200 and the Content-Type to text/html. Headers can
88
+ // be set at any time before the handler returns.
89
+
90
+ void cg_status(cg_res *res, int status);
91
+ void cg_set_header(cg_res *res, const char *name, const char *value); // replaces
92
+ void cg_add_header(cg_res *res, const char *name, const char *value); // appends
93
+ // attrs is appended as is, e.g. "Path=/; HttpOnly; Max-Age=3600".
94
+ void cg_set_cookie(cg_res *res, const char *name, const char *value, const char *attrs);
95
+
96
+ void cg_write(cg_res *res, const void *data, size_t len);
97
+ void cg_puts(cg_res *res, const char *s);
98
+ void cg_printf(cg_res *res, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
99
+ void cg_vprintf(cg_res *res, const char *fmt, va_list ap);
100
+
101
+ // Shortcuts: set the status and Content-Type, then write s.
102
+ void cg_text(cg_res *res, int status, const char *s);
103
+ void cg_html(cg_res *res, int status, const char *s);
104
+ void cg_json(cg_res *res, int status, const char *json);
105
+ void cg_redirect(cg_res *res, int status, const char *location);
106
+
107
+ // --- Strings ---------------------------------------------------------------
108
+ //
109
+ // These return new strings that live until the request ends. NULL in gives
110
+ // "" out, so cg_esc(cg_query(req, "q")) is safe.
111
+
112
+ char *cg_esc(const char *s); // escaped for HTML text and attributes
113
+ char *cg_json_str(const char *s); // a quoted JSON string literal
114
+ char *cg_url_encode(const char *s);
115
+ char *cg_sprintf(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
116
+
117
+ // Writes a line to the Worker's logs (stderr).
118
+ void cg_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
119
+
120
+ #endif