5 #include <yajl/yajl_gen.h>
12 yajl_gen_config yajl_c = { 0, 0 };
14 void respond_simple_data(unsigned const char *data, int len) {
15 printf("Content-length: %d\r\n\r\n", len);
20 printf("Status: 404 Not Found\r\n");
21 printf("Content-type: text/html\r\n");
22 printf("Content-length: %d\r\n\r\n", strlen(CONTENT_404));
28 printf("Status: 405 Method Not Allowed\r\n");
29 printf("Content-type: text/html\r\n");
30 printf("Content-length: %d\r\n\r\n", strlen(CONTENT_405));
35 void respond_JSON_Failure() {
36 respond_simple_data(JSON_FAILURE, strlen(JSON_FAILURE));
39 void respond_JSON_Success() {
40 respond_simple_data(JSON_SUCCESS, strlen(JSON_SUCCESS));
43 void respond_for_range(struct blerg *b, uint64_t from, uint64_t to) {
44 const unsigned char *ybuf;
49 uint64_t record_count = blerg_get_record_count(b);
51 printf("Content-type: application/json\r\n\r\n");
53 if (from > to || from >= record_count || to >= record_count || to - from > 99) {
54 respond_JSON_Failure();
58 g = yajl_gen_alloc(&yajl_c, NULL);
59 yajl_gen_array_open(g);
61 for (i = to; i != from - 1; i--) {
62 json_generate_one_record(g, NULL, b, i);
63 yajl_gen_get_buf(g, &ybuf, &len);
68 yajl_gen_array_close(g);
69 yajl_gen_get_buf(g, &ybuf, &len);
74 int main(int argc, char *argv[]) {
81 if (cgi_init() != CGIERR_NONE)
84 path = getenv("PATH_INFO");
89 request_method = getenv("REQUEST_METHOD");
91 if (strncmp(path, "/get", 4) == 0 && strlen(path) > 4) {
92 if (strncmp(request_method, "GET", 4) != 0) {
102 ret = parse_url_info(path + 5, &info);
103 if ((ret & URL_INFO_AUTHOR) == 0) {
108 if (!blerg_exists(info.author)) {
113 struct blerg *b = blerg_open(info.author);
115 if ((ret & URL_INFO_RECORD) && (ret & URL_INFO_RECORD_TO)) {
116 respond_for_range(b, info.record, info.record_to);
117 } else if (ret & URL_INFO_RECORD) {
118 ret = blerg_fetch(b, info.record, &data, &len);
124 respond_simple_data(data, len);
126 uint64_t record_count, from, to;
127 record_count = blerg_get_record_count(b);
128 if (record_count == 0) {
129 respond_simple_data("[]", 2);
131 to = record_count - 1;
132 from = (record_count > 50 ? to - 49 : 0);
133 respond_for_range(b, from, to);
138 } else if (strncmp(path, "/info", 5) == 0) {
139 if (strcmp(request_method, "GET") != 0) {
144 if (path[5] != '/') {
149 ret = parse_url_info(path + 6, &info);
150 if ((ret & URL_INFO_AUTHOR) == 0) {
155 if (!blerg_exists(info.author)) {
160 struct blerg *b = blerg_open(info.author);
161 uint64_t record_count = blerg_get_record_count(b);
165 yajl_gen g = yajl_gen_alloc(&yajl_c, NULL);
166 yajl_gen_map_open(g);
167 yajl_gen_string(g, "record_count", 12);
168 snprintf(number, 21, "%llu", record_count);
169 yajl_gen_string(g, number, strlen(number));
170 yajl_gen_map_close(g);
172 const unsigned char *ybuf;
173 yajl_gen_get_buf(g, &ybuf, &len);
175 printf("Content-type: application/json\r\n");
176 printf("Content-length: %d\r\n\r\n", len);