const http = require('http'); const fs = require('fs'); const path = require('path'); const zlib = require('zlib'); const DIST = '/home/pan/silk/web/dist'; const PORT = 5174; const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2', }; const server = http.createServer((req, res) => { console.log(`${req.method} ${req.url}`); // API proxy to NestJS if (req.url.startsWith('/api')) { const options = { hostname: '127.0.0.1', port: 3000, path: req.url, method: req.method, headers: { ...req.headers, host: 'localhost:3000' }, }; const proxy = http.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode, proxyRes.headers); proxyRes.pipe(res); }); proxy.on('error', (e) => { console.error('API proxy error:', e.message); res.writeHead(502, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Bad Gateway', detail: e.message })); }); req.pipe(proxy); return; } // Static file serving with gzip let urlPath = req.url.split('?')[0]; let filePath = path.join(DIST, urlPath === '/' ? 'index.html' : urlPath); if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { filePath = path.join(DIST, 'index.html'); } fs.readFile(filePath, (err, data) => { if (err) { res.writeHead(404); res.end('Not Found'); return; } const ext = path.extname(filePath); const contentType = MIME[ext] || 'application/octet-stream'; const acceptEncoding = req.headers['accept-encoding'] || ''; const useGzip = acceptEncoding.includes('gzip') && data.length > 1024; if (useGzip) { zlib.gzip(data, (err, compressed) => { if (err) { res.writeHead(500); res.end('Compression Error'); return; } res.writeHead(200, { 'Content-Type': contentType, 'Content-Encoding': 'gzip', 'Content-Length': compressed.length, 'Cache-Control': 'public, max-age=86400', }); res.end(compressed); }); } else { res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': data.length, 'Cache-Control': 'public, max-age=86400', }); res.end(data); } }); }); server.on('error', (e) => { console.error('Server error:', e); }); process.on('uncaughtException', (e) => { console.error('Uncaught:', e); }); server.listen(PORT, '0.0.0.0', () => { console.log(`Server running on http://0.0.0.0:${PORT} (gzip enabled)`); });