This commit is contained in:
蒋小陌 2024-11-06 21:16:35 +08:00
parent 5514a47ffb
commit cf106d1228
2 changed files with 31 additions and 5 deletions

File diff suppressed because one or more lines are too long

View File

@ -21,11 +21,15 @@ const viewsInfo = {
apiCall: 0,
// 缓存调用次数
cacheCall: 0,
// 缓存读取错误次数
cacheReadError: 0,
// API 调用错误次数
fetchApiError: 0,
};
// 默认端口号和 API 地址
let port = 9001;
let apiEndpoint = 'https://x-mo.cn:9001/get/';
let apiEndpoint = 'https://oss.x-php.com/get/';
// 解析命令行参数
args.forEach(arg => {
@ -170,7 +174,6 @@ const server = http.createServer(async (req, res) => {
// 修改 pathIndex 记录时,添加时间戳
pathIndex[uniqidhex] = { uniqid: data.uniqid, timestamp: Date.now() };
cacheMetaFile = pathModule.join(cacheDir, `${data.uniqid}.meta`);
cacheContentFile = pathModule.join(cacheDir, `${data.uniqid}.content`);
tempCacheContentFile = pathModule.join(cacheDir, `${data.uniqid}_${crypto.randomBytes(16).toString('hex')}.temp`);
@ -184,14 +187,28 @@ const server = http.createServer(async (req, res) => {
fetchAndServe(data, tempCacheContentFile, cacheContentFile, cacheMetaFile, res);
}
} else {
// 记录响应错误
viewsInfo.fetchApiError++;
// utf8 解码
res.writeHead(502, { 'Content-Type': 'text/plain;charset=UTF-8;' });
res.end(apiData.message || 'Bad Gateway');
}
} catch (error) {
res.writeHead(502, { 'Content-Type': 'text/plain;charset=UTF-8' });
// 记录响应错误
viewsInfo.fetchApiError++;
// 如果有缓存有忽略过期,直接调用
if (pathIndex[uniqidhex] && fs.existsSync(cacheMetaFile) && fs.existsSync(cacheContentFile)) {
serveFromCache(JSON.parse(fs.readFileSync(cacheMetaFile, 'utf8')), cacheContentFile, cacheMetaFile, res);
} else {
// utf8 解码
res.writeHead(502, { 'Content-Type': 'text/plain;charset=UTF-8;' });
res.end('Bad Gateway: Failed to decode JSON' + error);
}
}
}
});
@ -357,6 +374,11 @@ const serveFromCache = (cacheData, cacheContentFile, cacheMetaFile, res) => {
// 处理响应错误
const handleResponseError = (res, tempCacheContentFile, realUrl) => {
// 增加缓存读取错误次数
viewsInfo.cacheReadError++;
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'text/plain;charset=UTF-8' });
res.end(`Bad Gateway: ${realUrl}`);
@ -368,6 +390,10 @@ const handleResponseError = (res, tempCacheContentFile, realUrl) => {
// 处理缓存读取错误
const handleCacheReadError = (res) => {
// 增加缓存读取错误次数
viewsInfo.cacheReadError++;
if (!res.headersSent) {
res.writeHead(500, { 'Content-Type': 'text/plain;charset=UTF-8' });
res.end('Internal Server Error: Unable to read cache content file');