MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1#include <compat.h> // IWYU pragma: keep
2
3#include <stdio.h>
4#include <string.h>
5
6#include "ant.h"
7#include "modules/http_metadata.h"
8
9static const char *const http_methods[] = {
10 "ACL",
11 "BIND",
12 "CHECKOUT",
13 "CONNECT",
14 "COPY",
15 "DELETE",
16 "GET",
17 "HEAD",
18 "LINK",
19 "LOCK",
20 "M-SEARCH",
21 "MERGE",
22 "MKACTIVITY",
23 "MKCALENDAR",
24 "MKCOL",
25 "MOVE",
26 "NOTIFY",
27 "OPTIONS",
28 "PATCH",
29 "POST",
30 "PROPFIND",
31 "PROPPATCH",
32 "PURGE",
33 "PUT",
34 "QUERY",
35 "REBIND",
36 "REPORT",
37 "SEARCH",
38 "SOURCE",
39 "SUBSCRIBE",
40 "TRACE",
41 "UNBIND",
42 "UNLINK",
43 "UNLOCK",
44 "UNSUBSCRIBE"
45};
46
47typedef struct {
48 int code;
49 const char *text;
50} http_status_entry_t;
51
52static const http_status_entry_t http_status_codes[] = {
53 {200, "OK"},
54 {201, "Created"},
55 {202, "Accepted"},
56 {204, "No Content"},
57 {301, "Moved Permanently"},
58 {302, "Found"},
59 {303, "See Other"},
60 {304, "Not Modified"},
61 {307, "Temporary Redirect"},
62 {308, "Permanent Redirect"},
63 {400, "Bad Request"},
64 {401, "Unauthorized"},
65 {403, "Forbidden"},
66 {404, "Not Found"},
67 {405, "Method Not Allowed"},
68 {408, "Request Timeout"},
69 {409, "Conflict"},
70 {410, "Gone"},
71 {413, "Payload Too Large"},
72 {415, "Unsupported Media Type"},
73 {421, "Misdirected Request"},
74 {429, "Too Many Requests"},
75 {500, "Internal Server Error"},
76 {501, "Not Implemented"},
77 {502, "Bad Gateway"},
78 {503, "Service Unavailable"},
79 {504, "Gateway Timeout"}
80};
81
82static ant_value_t http_metadata_make_methods(ant_t *js) {
83 ant_value_t methods = js_mkarr(js);
84 size_t count = sizeof(http_methods) / sizeof(http_methods[0]);
85
86 for (size_t i = 0; i < count; i++) {
87 js_arr_push(js, methods, js_mkstr(js, http_methods[i], strlen(http_methods[i])));
88 }
89
90 return methods;
91}
92
93static ant_value_t http_metadata_make_status_codes(ant_t *js) {
94 ant_value_t status_codes = js_mkobj(js);
95
96 size_t count = sizeof(http_status_codes) / sizeof(http_status_codes[0]);
97 char code_buf[16];
98
99 for (size_t i = 0; i < count; i++) {
100 int code = http_status_codes[i].code;
101 size_t code_len = (size_t)snprintf(code_buf, sizeof(code_buf), "%d", code);
102
103 js_setprop(
104 js, status_codes,
105 js_mkstr(js, code_buf, code_len),
106 js_mkstr(js, http_status_codes[i].text, strlen(http_status_codes[i].text))
107 );
108 }
109
110 return status_codes;
111}
112
113ant_value_t internal_http_metadata_library(ant_t *js) {
114 ant_value_t lib = js_mkobj(js);
115
116 js_set(js, lib, "METHODS", http_metadata_make_methods(js));
117 js_set(js, lib, "STATUS_CODES", http_metadata_make_status_codes(js));
118
119 return lib;
120}