Created
May 22, 2021 10:53
-
-
Save lbr77/2c2857b15818f4df21582c7f046af9c3 to your computer and use it in GitHub Desktop.
CDN开源
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
addEventListener("fetch", event => { | |
event.respondWith(handleRequest(event)) | |
}) | |
const BUCKET_NAME = "lbr77/CDN@main" | |
const BUCKET_URL = `http://cdn.jsdelivr.net/gh/${BUCKET_NAME}` | |
async function serveAsset(event) { | |
const url = new URL(event.request.url) | |
const cache = caches.default | |
let response = await cache.match(event.request) | |
if (!response) { | |
response = await fetch(`${BUCKET_URL}${url.pathname}`) | |
const headers = { "cache-control": "public, max-age=14400"} | |
response = new Response(response.body, { ...response, headers }) | |
event.waitUntil(cache.put(event.request, response.clone())) | |
} | |
return response | |
} | |
async function handleRequest(event) { | |
if (event.request.method === "GET") { | |
let url = new URL(event.request.url); | |
if (url.pathname === "/") { | |
return Response.redirect("https://github.com/lbr77/CDN", 301) | |
} | |
else if (url.pathname.startsWith("/pixiv")) { | |
url.hostname = "i.pximg.net"; | |
url.pathname = url.pathname.slice("6"); | |
let request = new Request(url, event.request); | |
let response = await fetch(request, { | |
headers: { | |
'Referer': 'https://www.pixiv.net/', | |
'User-Agent': 'Cloudflare Workers' | |
} | |
}); | |
const headers = { "cache-control": "public, max-age=14400" } | |
response = new Response(response.body, { ...response, headers }) | |
// event.waitUntil(cache.put(event.request, response.clone())) | |
return response | |
} | |
let response = await serveAsset(event) | |
if (response.status > 399) { | |
response = new Response(response.statusText, { status: response.status }) | |
} | |
return response | |
} else { | |
return new Response("Method not allowed", { status: 405 }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment