| 1 | const fs = require('fs'); |
| 2 | const path = require('path'); |
| 3 | const respond = require('../lib/respond'); |
| 4 | |
| 5 | const PUBLIC = path.join(__dirname, '..', 'public'); |
| 6 | const 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 | |
| 15 | const cache = {}; |
| 16 | |
| 17 | for (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 | |
| 23 | function 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 | |
| 35 | module.exports = function register(router) { |
| 36 | for (const urlPath of Object.keys(cache)) { |
| 37 | router.get(urlPath, serve); |
| 38 | } |
| 39 | }; |
| 40 | |