Skip to content

Instantly share code, notes, and snippets.

@shagamemnon
Created May 7, 2018 21:14
Show Gist options
  • Save shagamemnon/a083ab5306ecc10b2b5239899c2800df to your computer and use it in GitHub Desktop.
Save shagamemnon/a083ab5306ecc10b2b5239899c2800df to your computer and use it in GitHub Desktop.
/**
* IMPORTANT NOTE:
* When you try to run 301/302 redirects using Workers, the preview
* browser on the right of this script will throw an error. Disregard it!
*
* The script will function properly. The reason the preview browser runs
* into this problem is that it's actually trying to redirect you, but
* the Cloudflare dashboard is ensuring that you stay on the page to finish
* your code
*
* DOCUMENTATION:
* https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
* https://developer.mozilla.org/en-US/docs/Web/API/Response/Response
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// We can separate the different components of a URL string like this:
const incomingURI = new URL(request.url)
const hostName = incomingURI.host
const pathName = incomingURI.pathname
const protocol = incomingURI.protocol
const queryParams = incomingURI.search
console.log(`${protocol}//${hostName}${pathName}?${queryParams}`)
// Declate the "response" variable
let response
// Evaluate each "case" for a "true" response. If a true response is found,
// assign a value to the response variable, "break" the switch condition
// and return the response.
// If none of these conditions match, execute the original request
switch (true) {
case queryParams.includes('author=bob'):
response = Response.redirect('https://google.com', 301)
break
case hostName.includes('123.example.com'):
response = Response.redirect('https://www.example.com', 301)
break
case pathName.includes('/path/bill'):
response = Response.redirect('https://www.example.com/bob', 301)
break
default:
return fetch(request)
}
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment