Skip to content

Instantly share code, notes, and snippets.

@zsnmwy
Created May 11, 2021 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zsnmwy/129031223d73ce76d1a513719e3c90e5 to your computer and use it in GitHub Desktop.
Save zsnmwy/129031223d73ce76d1a513719e3c90e5 to your computer and use it in GitHub Desktop.
const BASE_DOMAIN = ""
addEventListener('fetch', function (event) {
const { request } = event
const response = handleRequest(request).catch(handleError)
event.respondWith(response)
})
/**
* Receives a HTTP request and replies with a response.
* @param {Request} request
* @returns {Promise<Response>}
*/
async function handleRequest(request) {
const { method, url } = request
const { host, pathname } = new URL(url)
let matchStatus = -1
// https://gist.github.com/BexTuychiev/ad0b1318a392691a74666fd34171afb2.js
const reMatchJS = /\/(.*)\/(.*).js$/
// https://github.githubassets.com/assets/gist-embed-ceaaa09008a5bc2758b9ee6a1c99082d.css
const reMatchCssAssets = /\/assets\/(.*)/
if(reMatchJS.test(pathname)) matchStatus = 1;
if(reMatchCssAssets.test(pathname)) matchStatus = 2;
console.log(pathname, matchStatus, reMatchJS.test(pathname))
switch (matchStatus) {
case 1:
return await proxyJS(pathname);
case 2:
return await proxyCSS(pathname);
default:
return new Response(`Not match path ${pathname}. \nPlease check it`, {status: 409})
}
}
async function proxyJS(pathname) {
console.log('proxy js')
const base = "https://gist.github.com"
return await fetchContent(base, pathname, true, 'github.githubassets.com', BASE_DOMAIN)
}
async function proxyCSS(pathname) {
console.log('proxy css')
const base = "https://github.githubassets.com"
return await fetchContent(base, pathname)
}
async function fetchContent(base, pathname, isReplace = false, re, reContent) {
const url = base + pathname
const myRequest = new Request(url)
const proxyData = await fetch(myRequest)
const { status, statusText, body} = proxyData
if(status != 200) return new Response('Error From Github: ' + statusText, {status: status})
if(isReplace) {
let originText = await proxyData.text()
originText = originText.replace(re,reContent);
return new Response(originText, {status: 200})
} else {
return new Response(body, {status: 200})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment