Go + PostgreSQL + Valkey backend (cmd/internal/migrations), uni-app mobile frontend, PC web (web/), admin console (admin/), Android WebView container (android_project/). Build artifacts, node_modules, local env and debug screenshots excluded.
80 lines
2.4 KiB
JavaScript
80 lines
2.4 KiB
JavaScript
import http from 'node:http';
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||
const distDir = path.resolve(__dirname, 'dist', 'build', 'h5');
|
||
const PORT = process.env.STATIC_PORT || 3001;
|
||
|
||
const MIME_TYPES = {
|
||
'.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',
|
||
'.jpg': 'image/jpeg',
|
||
'.jpeg': 'image/jpeg',
|
||
'.gif': 'image/gif',
|
||
'.svg': 'image/svg+xml',
|
||
'.ico': 'image/x-icon',
|
||
'.woff': 'font/woff',
|
||
'.woff2': 'font/woff2',
|
||
'.ttf': 'font/ttf',
|
||
};
|
||
|
||
const server = http.createServer((req, res) => {
|
||
let reqPath = decodeURIComponent(req.url?.split('?')[0] || '/');
|
||
if (reqPath === '/' || reqPath === '') {
|
||
reqPath = '/index.html';
|
||
}
|
||
|
||
const filePath = path.join(distDir, reqPath);
|
||
|
||
// 安全检查:防止路径穿越
|
||
if (!filePath.startsWith(distDir)) {
|
||
res.statusCode = 403;
|
||
res.end('Forbidden');
|
||
return;
|
||
}
|
||
|
||
fs.stat(filePath, (err, stats) => {
|
||
if (err || !stats.isFile()) {
|
||
// SPA fallback 到 index.html
|
||
const fallbackPath = path.join(distDir, 'index.html');
|
||
fs.readFile(fallbackPath, (fallbackErr, data) => {
|
||
if (fallbackErr) {
|
||
res.statusCode = 404;
|
||
res.end('Not Found');
|
||
} else {
|
||
res.statusCode = 200;
|
||
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
||
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
|
||
res.end(data);
|
||
}
|
||
});
|
||
return;
|
||
}
|
||
|
||
const ext = path.extname(filePath).toLowerCase();
|
||
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
|
||
|
||
res.statusCode = 200;
|
||
res.setHeader('Content-Type', contentType);
|
||
|
||
// index.html 绝不缓存,避免用户拿到旧 bundle;
|
||
// 带哈希的 assets 可以长缓存(文件名变了 URL 就变了)
|
||
if (reqPath === '/index.html' || ext === '.html') {
|
||
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
|
||
} else {
|
||
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
|
||
}
|
||
|
||
fs.createReadStream(filePath).pipe(res);
|
||
});
|
||
});
|
||
|
||
server.listen(PORT, '0.0.0.0', () => {
|
||
console.log(`Frontend H5 static server running at http://127.0.0.1:${PORT}`);
|
||
});
|