async function startServer(req, res) {
try {
const method = req.method?.toUpperCase() as 'GET' | 'POST' | 'PUT' | 'DELETE';
if (!method || !nile.handlers[method]) {
res.writeHead(405, { 'Content-Type': 'text/plain' });
return res.end('Method Not Allowed');
}
const url = `http://${req.headers.host}${req.url}`;
const bodyChunks: Uint8Array[] = [];
req.on('data', chunk => bodyChunks.push(chunk));
req.on('end', async () => {
const body = Buffer.concat(bodyChunks);
const request = new Request(url, {
method,
headers: req.headers as HeadersInit,
body: method === 'POST' || method === 'PUT' ? body : undefined,
});
let response;
try {
response = await nile.handlers[method](request);
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
return res.end('Internal Server Error');
}
res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
const respBody = await response.text();
res.end(respBody);
});
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Unexpected Server Error');
}
};