benchmarks/http_reference.c
/* Same synchronous router and network primitives as examples/http_server.bas. */
#include "network.h"
static Word literal(const char *s) {
return new_buffer(s, strlen(s), strlen(s), 1);
}
int main(int argc, char **argv) {
Word port = argument(argc == 2 ? argv[1] : NULL);
Word listener = bs_tcp_listen((Word[]){literal("127.0.0.1"), port});
if (listener & SIGN_BIT) return 1;
print_word(bs_tcp_port(&listener));
fflush(stdout);
Word req = bs_buffer((Word[]){8192});
Word root = literal("GET / "), health = literal("GET /health "), get = literal("GET ");
Word html = literal("text/html; charset=utf-8"), text = literal("text/plain");
Word page = literal("<!doctype html><title>Basalt</title><h1>Hello from Basalt</h1>\n");
Word ok = literal("ok\n"), missing = literal("Page not found\n"), method = literal("Use GET\n");
Word invalid = literal("Invalid or incomplete headers\n");
for (;;) {
Word fd = bs_tcp_accept(&listener);
if (fd & SIGN_BIT) break;
Word n = bs_http_headers((Word[]){fd, req});
if (n & SIGN_BIT) {
bs_http_reply((Word[]){fd, 400, text, invalid});
} else if (n) {
if (bs_starts_with((Word[]){req, root})) bs_http_reply((Word[]){fd, 200, html, page});
else if (bs_starts_with((Word[]){req, health})) bs_http_reply((Word[]){fd, 200, text, ok});
else if (bs_starts_with((Word[]){req, get})) bs_http_reply((Word[]){fd, 404, text, missing});
else bs_http_reply((Word[]){fd, 405, text, method});
}
bs_tcp_close(&fd);
}
return 1;
}