rewrite without express

This commit is contained in:
Erin 2023-09-05 21:40:09 -04:00
parent 5a5dbce8ed
commit f2f51b28fe
3 changed files with 25 additions and 1051 deletions

View file

@ -1,30 +1,30 @@
import * as fs from 'node:fs'; import {readFileSync} from 'node:fs';
import express from 'express'; import {createServer} from 'node:http';
import {URL} from 'node:url';
const sites = fs.readFileSync('./webring.txt', 'utf-8') const data = readFileSync(process.env.SITES_FILE || 'webring.txt', 'utf-8');
// split lines const sites = [...data.matchAll(/^\s*([^#\s].*)\s*$/gm)].map(match => match[1]);
.split(/\r?\n/)
// trim whitespace from each line
.map(site => site.trim())
// exclude empty lines and lines that start with # because why not
.filter(site => site && !site.startsWith('#'));
// modulo that does the right thing with negatives const text = (response, body, code = 200) => {
// https://stackoverflow.com/a/4467559 response.writeHead(code, {'Content-Type': 'text/plain'}).write(body);
const mod = (n, m) => ((n % m) + m) % m; response.end();
};
const redirect = (res, url) => res.writeHead(301, {Location: url}).end();
function handle (offset, request, response) { const toSite = (response, from, offset) => {
const from = request.query.from;
const index = sites.findIndex(site => site === from); const index = sites.findIndex(site => site === from);
if (!from || index === -1) { if (!from || index === -1) {
response.status(400).send('the provided site is not in the webring'); return text(response, 'the provided site is not in the webring', 400);
return;
} }
response.redirect(301, sites[mod(index + offset, sites.length)]); redirect(response, sites[(index + offset + sites.length) % sites.length]);
} };
express() const pathHandlers = {
.get('/prev', (request, response) => handle(-1, request, response)) '/prev': (response, query) => toSite(response, query.get('from'), -1),
.get('/next', (request, response) => handle(+1, request, response)) '/next': (response, query) => toSite(response, query.get('from'), +1),
.get('/list', (_, response) => response.type('txt').send(sites.join('\n'))) '/list': response => text(response, sites.join('\n')),
.listen(process.env.PORT || 8080); };
createServer((request, response) => {
const url = new URL(request.url, `http://${request.headers.host}`);
pathHandlers[url.pathname]?.(response, url.searchParams);
}).listen(process.env.PORT || 80);

1025
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -8,8 +8,5 @@
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
"license": "ISC", "license": "ISC"
"dependencies": {
"express": "^4.18.2"
}
} }