routes/static.js - git - Webernet Explorer _X
git 🏠 Home 👤 Sign up Self hosted git, retro shell
★ otgit, code hosting from the year 2000 ★
📄 octuna / routes / static.js
40 lines · 1.0 KB · Raw
1const fs = require('fs');
2const path = require('path');
3const respond = require('../lib/respond');
4 
5const PUBLIC = path.join(__dirname, '..', 'public');
6const MIME = {
7 css: 'text/css',
8 js: 'text/javascript',
9 png: 'image/png',
10 ico: 'image/x-icon',
11 svg: 'image/svg+xml',
12 txt: 'text/plain'
13};
14 
15const cache = {};
16 
17for (const name of fs.readdirSync(PUBLIC)) {
18 const ext = path.extname(name).slice(1).toLowerCase();
19 const type = MIME[ext] || 'application/octet-stream';
20 cache['/' + name] = { body: fs.readFileSync(path.join(PUBLIC, name)), type };
21}
22 
23function serve(req, res) {
24 const f = cache[req.url.split('?')[0]];
25 if (!f) return respond.notFound(res);
26 res.writeHead(200, {
27 'Content-Type': f.type,
28 'Content-Length': f.body.length,
29 'Cache-Control': 'public, max-age=3600',
30 ...respond.securityHeaders()
31 });
32 res.end(f.body);
33}
34 
35module.exports = function register(router) {
36 for (const urlPath of Object.keys(cache)) {
37 router.get(urlPath, serve);
38 }
39};
40 
Done 🔒 Internet