From 15a9a009a38b057cee41004de677dd4b32f6626a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=92=8B=E5=B0=8F=E9=99=8C?= Date: Fri, 27 Sep 2024 19:00:46 +0800 Subject: [PATCH] 1111 --- index.js | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index 269b9c8..24197cb 100644 --- a/index.js +++ b/index.js @@ -56,8 +56,8 @@ const server = http.createServer(async (req, res) => { try { const apiData = await fetchApiData(reqPath, sign); if (apiData.code === 200 && apiData.data && apiData.data.url) { - const { url: realUrl, cloudtype, expiration, path } = apiData.data; - const data = { realUrl, cloudtype, expiration: expiration * 1000, path }; + const { url: realUrl, cloudtype, expiration, path, headers, uniqid } = apiData.data; + const data = { realUrl, cloudtype, expiration: expiration * 1000, path, headers, uniqid }; if (expiration > 0) { fs.writeFileSync(cacheMetaFile, JSON.stringify(data)); @@ -120,21 +120,22 @@ const fetchApiData = (reqPath, sign) => { const fetchAndServe = (data, tempCacheContentFile, cacheContentFile, res) => { https.get(data.realUrl, { timeout: requestTimeout * 10 }, (realRes) => { + // 创建临时缓存文件流 const cacheStream = fs.createWriteStream(tempCacheContentFile, { flags: 'w' }); // 通过 data.path 判断是否是视频.mp4 const isVideo = data.path.includes('.mp4'); - // realRes.headers['content-type'] 有的话 去掉 - if (realRes.headers['content-type']) { - delete realRes.headers['content-type']; - } - res.writeHead(realRes.statusCode, { - ...realRes.headers, + ...data.headers, 'Content-Type': isVideo ? 'video/mp4' : 'application/octet-stream', 'Cloud-Type': data.cloudtype, 'Cloud-Expiration': data.expiration, + // 添加缓存, 浏览器缓存不再重复请求 + 'Cache-Control': 'public, max-age=31536000', + 'Expires': new Date(Date.now() + 31536000000).toUTCString(), + 'Last-Modified': new Date().toUTCString(), + 'ETag': data.uniqid || '' }); realRes.pipe(cacheStream); @@ -165,15 +166,19 @@ const fetchAndServe = (data, tempCacheContentFile, cacheContentFile, res) => { const serveFromCache = (cacheMetaFile, cacheContentFile, res) => { const cacheData = JSON.parse(fs.readFileSync(cacheMetaFile, 'utf8')); const readStream = fs.createReadStream(cacheContentFile); - // 判断是否是视频 const isVideo = cacheData.path.includes('.mp4'); - readStream.on('open', () => { res.writeHead(200, { + ...cacheData.headers, 'Content-Type': isVideo ? 'video/mp4' : 'application/octet-stream', 'Cloud-Type': cacheData.cloudtype, 'Cloud-Expiration': cacheData.expiration, + // 添加缓存, 浏览器缓存不再重复请求 + 'Cache-Control': 'public, max-age=31536000', + 'Expires': new Date(Date.now() + 31536000000).toUTCString(), + 'Last-Modified': new Date().toUTCString(), + 'ETag': cacheData.uniqid || '' }); readStream.pipe(res); });