42 lines
1.7 KiB
JavaScript
42 lines
1.7 KiB
JavaScript
"use strict";
|
|
const http = require("node:http");
|
|
const messages = require("./messages.json");
|
|
|
|
function pickLang(req) {
|
|
const q = new URL(req.url, "http://x").searchParams.get("lang");
|
|
if (q && messages[q]) return q;
|
|
const al = String(req.headers["accept-language"] || "").toLowerCase();
|
|
for (const l of Object.keys(messages)) if (al.startsWith(l)) return l;
|
|
return "ru";
|
|
}
|
|
|
|
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
|
|
function page(lang) {
|
|
const m = messages[lang];
|
|
return `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(m.title)}</title></head><body style="font-family:sans-serif;max-width:40rem;margin:2rem auto;padding:0 1rem"><h1>${esc(m.title)}</h1><h2>${esc(m.whatTitle)}</h2><p>${esc(m.what)}</p><h2>${esc(m.useTitle)}</h2><p>${esc(m.use)}</p><h2>${esc(m.checkTitle)}</h2><p>${esc(m.check)}</p></body></html>`;
|
|
}
|
|
|
|
function createServer() {
|
|
return http.createServer((req, res) => {
|
|
const path = new URL(req.url, "http://x").pathname;
|
|
if (path === "/healthz") {
|
|
res.writeHead(200, { "content-type": "text/plain" });
|
|
return res.end("ok");
|
|
}
|
|
const lang = pickLang(req);
|
|
if (path === "/") {
|
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
return res.end(page(lang));
|
|
}
|
|
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
|
res.end(messages[lang].notFound);
|
|
});
|
|
}
|
|
|
|
if (require.main === module) {
|
|
const port = Number(process.env.PORT) || 3000;
|
|
createServer().listen(port, "0.0.0.0", () => console.log(`listening on ${port}`));
|
|
}
|
|
module.exports = { createServer };
|