aboutsummaryrefslogtreecommitdiffstats
path: root/claude-julia/server.ts
blob: e01a02ca2f946d33e737b84e0166650ceaf4cdd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import * as http from "http";
import * as fs from "fs";

import { query } from "./query";

const hostname = "";
const port = 3000;

function readFiles(l: Array<string>) {
	let m = new Map<string,ArrayBuffer>();
	for (const fn of l) {
		m.set(fn, fs.readFileSync(fn));
	}
	return m;
}

const files: Map<string,ArrayBuffer> = readFiles(["index.html", "style.css", "client.js"]);

async function readBody(req: http.IncomingMessage): Promise<string> {
	return new Promise((resolve, reject) => {
		let chunks: Buffer[] = [];
		req.on('data', (chunk: Buffer) => {
			chunks.push(chunk);
		});
		req.on('end', () => {
			resolve(Buffer.concat(chunks).toString());
		});
	});
}

const server = http.createServer(async (req: http.IncomingMessage,res) => {
	switch (req.url) {
		case "/":
			res.statusCode = 200;
			res.end(files.get("index.html"));
			break;
		case "/style.css":
			res.statusCode = 200;
			res.end(files.get("style.css"));
			break;
		case "/client.js":
			res.statusCode = 200;
			res.end(files.get("client.js"));
			break;
		case "/query":
			if (req.method !== 'POST') {
				res.statusCode = 405;
				res.end('Must use POST');
				return;
			}
			res.statusCode = 200;
			let body = await readBody(req);
			let response = await query(body);
			res.end(response);
			break;
		default:
			res.statusCode = 404;
			res.setHeader('Content-Type', 'text/html');
			res.end('Not found!');
	}
});

server.listen(port, hostname, () => {});