const http = require('http');
const https = require('https');
const PORT = process.env.PORT || 7000;
const getContentType = (headers) => {
const contentType = headers['content-type'];
return contentType || 'text/plain';
};
const handleRequest = (req, res) => {
try {
const reqUrl = new URL(req.url, `http://${req.headers.host}`); // 使用 `new URL()` 解析
const path = reqUrl.pathname;
if (path.startsWith('/')) {
const githubUrl = `https://raw.githubusercontent.com${path}`;
https.get(githubUrl, (githubRes) => {
res.writeHead(githubRes.statusCode, {
'Content-Type': getContentType(githubRes.headers),
'Access-Control-Allow-Origin': '*', // 允许跨域访问,根据需要调整
'Access-Control-Allow-Methods': 'GET', // 允许的请求方法,根据需要调整
});
githubRes.on('data', (chunk) => {
res.write(chunk);
});
githubRes.on('end', () => {
res.end();
});
}).on('error', (err) => {
console.error(err);
res.writeHead(500);
res.end('Error fetching resource from GitHub.');
});
} else {
res.writeHead(400);
res.end('Invalid request.');
}
} catch (err) {
console.error('Error parsing URL:', err);
res.writeHead(400);
res.end('Invalid URL.');
}
};
const server = http.createServer(handleRequest);
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});