Skip to content

Instantly share code, notes, and snippets.

@pengelana
Last active July 22, 2024 00:46
Show Gist options
  • Save pengelana/dd85d0a076ddfd8d85cee10535696cb5 to your computer and use it in GitHub Desktop.
Save pengelana/dd85d0a076ddfd8d85cee10535696cb5 to your computer and use it in GitHub Desktop.
cacheall
/* cacheall */
async function handleRequest(event) {
let request = event.request
let cacheKey = request
let url = new URL(request.url)
if (request.method.toUpperCase() === 'POST') {
let string = '';
(new Uint8Array(await request.arrayBuffer())).forEach(
(byte) => { string += String.fromCharCode(byte) }
)
string = await encode_safe_64(string)
url += '?dns=' + string
cacheKey = new Request(url, {
headers: request.headers,
method: 'GET',
})
} else {
cacheKey = request
}
response = await fetch(cacheKey, { cf: { cacheEverything: true } })
return response
}
addEventListener('fetch', event => {
event.passThroughOnException()
return event.respondWith(handleRequest(event))
})
async function encode_safe_64(buffer) {
return btoa(buffer)
.replace(/\+/g, '-') // Convert '+' to '-'
.replace(/\//g, '_') // Convert '/' to '_'
.replace(/=+$/, ''); // Remove ending '='
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment