fix: 优化代码

This commit is contained in:
2024-10-11 23:47:34 +08:00
parent f0468539dc
commit c92f817d66
3 changed files with 70 additions and 23 deletions

View File

@@ -17,7 +17,6 @@ const { api, domain, allowedOrigins } = useConfig<{
}>();
const fileStore = useFileStore('upload');
console.log('filePath', fileStore);
const noProxyUrl = ['/', '/favicon.ico'];
export const handleRequest = async (req: http.IncomingMessage, res: http.ServerResponse) => {
const dns = getDNS(req);
@@ -42,7 +41,6 @@ export const handleRequest = async (req: http.IncomingMessage, res: http.ServerR
// app = 'codeflow';
// domainApp = true;
} else {
// 生产环境
// 验证域名
if (dns.hostName !== domain) {
// redis获取域名对应的用户和应用
@@ -172,6 +170,14 @@ export const handleRequest = async (req: http.IncomingMessage, res: http.ServerR
const [indexFilePath, etag] = indexFile.split('||');
const contentType = getContentType(indexFilePath);
const isHTML = contentType.includes('html');
const filePath = path.join(fileStore, indexFilePath);
if (!userApp.fileCheck(filePath)) {
res.writeHead(500, { 'Content-Type': 'text/html' });
res.write('File expired, Not Found\n');
res.end();
await userApp.clearCacheData();
return;
}
// 如果 content是 'application/octet-stream' 会下载文件, 添加文件后缀
if (contentType === 'application/octet-stream') {
// 提取文件名,只保留文件名而不是整个路径
@@ -181,9 +187,9 @@ export const handleRequest = async (req: http.IncomingMessage, res: http.ServerR
// 不存在的文件,返回indexFile的文件
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': isHTML ? 'no-cache' : 'public, max-age=3600' });
const filePath = path.join(fileStore, indexFilePath);
const readStream = fs.createReadStream(filePath);
readStream.pipe(res);
return;
} else {
const [appFilePath, eTag] = appFile.split('||');
@@ -207,8 +213,17 @@ export const handleRequest = async (req: http.IncomingMessage, res: http.ServerR
'Cache-Control': isHTML ? 'no-cache' : 'public, max-age=3600', // 设置缓存时间为 1 小时
ETag: eTag,
});
if (!userApp.fileCheck(filePath)) {
console.error('File expired', filePath);
res.writeHead(500, { 'Content-Type': 'text/html' });
res.write('File expired\n');
res.end();
await userApp.clearCacheData();
return;
}
const readStream = fs.createReadStream(filePath);
readStream.pipe(res);
return;
}
};