Skip to content

Instantly share code, notes, and snippets.

@LittleChest
Last active March 20, 2024 17:15
Show Gist options
  • Save LittleChest/e0e231f0310c1bd3f58268c1bd41f2b1 to your computer and use it in GitHub Desktop.
Save LittleChest/e0e231f0310c1bd3f58268c1bd41f2b1 to your computer and use it in GitHub Desktop.
// 万物起源
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
// 主逻辑
async function handleRequest(request) {
const url = new URL(request.url);
const path = url.pathname;
const otaResponse = await ROMS.get(`OTA_${path}`);
if (otaResponse) {
return new Response((otaResponse), {
headers: { 'Content-Type': 'application/json' },
});
} else {
const country = request.cf.country;
if (country === 'CN') {
return fileChina(request)
} else {
return fileGlobal(request)
}
}
}
// 中国文件存储
async function fileChina(request) {
const url = new URL(request.url);
const fileParam = url.searchParams.get('file');
if (fileParam) {
const redirectUrl = await ROMS.get(`CHINA_${fileParam}`);
if (redirectUrl) {
// 使用301跳转以支持Updater
// return Response.redirect(redirectUrl, 301);
const response = await fetch(redirectUrl);
return Response.redirect(response.url, 301);
} else {
// 简体中文返回
return new Response('\
我们无法找到您请求的文件,这可能由于文件过于久远已被删除或输入的链接不正确。\n\
您可以与开发人员联系,喵~',
{
status: 404,
headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
});
}
} else {
// 返回418
return new Response('\
我们无法处理您的请求,这可能由于您输入了错误的参数。\n\
您可以与开发人员联系,喵~',
{
status: 418,
headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
});
}
}
// 全球文件存储
async function fileGlobal(request) {
const url = new URL(request.url);
const fileParam = url.searchParams.get('file');
if (fileParam) {
const redirectUrl = await ROMS.get(`GLOBAL_${fileParam}`);
if (redirectUrl) {
// 使用301跳转以支持Updater
return Response.redirect(redirectUrl, 301);
} else {
// English返回
return new Response('\
We were unable to find the file you requested, either because it is too old and has been deleted or because the link entered was incorrect.\n\
You can contact the dev, nya~',
{
status: 404,
headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
});
}
} else {
// 返回418
return new Response('\
We were unable to complete your request, possibly because you entered incorrect parameters.\n\
You can contact the dev, nya~',
{
status: 418,
headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment