Skip to content

Instantly share code, notes, and snippets.

@troyhunt
Created September 4, 2018 23:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troyhunt/ad2c7d562b8221c2e1aa3bd58f149e9f to your computer and use it in GitHub Desktop.
Save troyhunt/ad2c7d562b8221c2e1aa3bd58f149e9f to your computer and use it in GitHub Desktop.
Cloudflare Worker to normalise URLs for cache efficiency
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
})
/**
* Fetch request after making casing of hash prefix uniform
* @param {Request} request
*/
async function handleRequest(request) {
if(request.method === 'OPTIONS') {
let responseHeaders = setCorsHeaders(new Headers())
return new Response('', {headers:responseHeaders})
}
const url = new URL(request.url);
if (!url.pathname.startsWith("/range/")) {
const response = await fetch(request)
return response;
}
const prefix = url.pathname.substr(7);
const newRequest = "https://api.pwnedpasswords.com/range/" + prefix.toUpperCase()
if (prefix === prefix.toUpperCase()) {
const response = await fetch(request, { cf: { cacheKey: newRequest } })
return response;
}
const init = {
method: request.method,
headers: request.headers
}
const modifiedRequest = new Request(newRequest, init)
const response = await fetch(modifiedRequest, { cf: { cacheKey: newRequest } })
return response
}
function setCorsHeaders(headers) {
headers.set('Access-Control-Allow-Origin', '*')
headers.set('Access-Control-Allow-Methods', 'GET')
headers.set('Access-Control-Allow-Headers', 'access-control-allow-headers')
headers.set('Access-Control-Max-Age', 1728000)
return headers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment