f0ckv2/src/websrv.mjs

44 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-04-25 18:00:47 +00:00
import http from "http";
import url from "url";
import querystring from "querystring";
import cfg from "../config.json";
2020-04-02 02:35:28 +00:00
import router from "./inc/router.mjs";
2019-04-25 18:00:47 +00:00
// routes
2020-04-02 02:35:28 +00:00
import "./inc/routes/index.mjs";
import "./inc/routes/api.mjs";
import "./inc/routes/static.mjs";
2020-04-07 08:07:47 +00:00
import "./inc/routes/stats.mjs";
2019-04-25 18:00:47 +00:00
2020-04-02 02:35:28 +00:00
http.createServer(async (req, res, r) => {
2020-04-06 11:49:53 +00:00
const t_start = process.hrtime();
req.url = url.parse(req.url.replace(/(?!^.)(\/+)?$/, ''));
req.url.split = req.url.pathname.split("/").slice(1);
req.url.qs = querystring.parse(req.url.query);
2020-04-02 02:35:28 +00:00
req.post = new Promise((resolve, _, data = "") => req
.on("data", d => void (data += d))
.on("end", () => void resolve(Object.fromEntries(Object.entries(querystring.parse(data)).map(([k, v]) => [k, decodeURIComponent(v)])))));
res.reply = ({
code = 200,
type = "text/html",
body
}) => res.writeHead(code, { "Content-Type": `${type}; charset=utf-8` }).end(body);
2020-04-06 11:15:29 +00:00
res.redirect = target => res.writeHead(301, {
"Cache-Control": "no-cache, public",
"Location": target
}).end();
2020-04-02 02:35:28 +00:00
!(r = router.routes.getRoute(req.url.pathname, req.method)) ? res.writeHead(404).end(`404 - ${req.url.pathname}`) : await r(req, res);
2020-04-07 08:07:47 +00:00
console.log([
`[${(new Date()).toLocaleTimeString()}]`,
`${(process.hrtime(t_start)[1] / 1e6).toFixed(2)}ms`,
`${req.method} ${res.statusCode}`,
req.url.pathname].map(e=>e.toString().padEnd(15)).join(""));
2020-04-02 02:35:28 +00:00
}).listen(cfg.websrv.port, () => setTimeout(() => {
console.log(`f0ck is listening on port ${cfg.websrv.port}.`);
}, 500));