Last active
September 30, 2019 15:15
-
-
Save alexgibson/3425f57088d6fde02b6f0797eb738e08 to your computer and use it in GitHub Desktop.
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
/* This Source Code Form is subject to the terms of the Mozilla Public | |
* License, v. 2.0. If a copy of the MPL was not distributed with this | |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | |
async function handleRequest(request) { | |
// The % of traffic we want to redirect (e.g. 0.05 == 5%) | |
const SAMPLE_RATE = 0.05; | |
// The current domain (e.g. 'https://www.allizom.org', 'https://www.mozilla.org'). | |
const domain = 'https://www.allizom.org'; | |
// The URL we're targeting. | |
const targetURL = `${domain}/en-US/firefox/new/`; | |
// The experimental URL we want to redirect to. | |
const experimentURL = `${domain}/en-US/exp/firefox/new/`; | |
// The website visitor's current URL. | |
const currentURL = request.url; | |
/** | |
* Matches the current URL to the URL we're targeting. | |
* If a match is found, then return a final URL for the | |
* experimental page, preserving any original URL parameters. | |
*/ | |
function getFinalURL(currentURL, targetURL, experimentURL) { | |
const url = currentURL.split('?'); | |
// is the current URL what we're explicitly targeting? | |
if (url[0] === targetURL) { | |
// preserve query params from current URL if they exist. | |
const params = url.length > 1 ? url[1] : null; | |
if (params) { | |
return `${experimentURL}?${params}`; | |
} | |
return experimentURL; | |
} else { | |
return false; | |
} | |
} | |
function isWithinSampleRate(SAMPLE_RATE) { | |
return Math.random() < SAMPLE_RATE; | |
} | |
function isValidURL(finalURL, experimentURL) { | |
return finalURL && finalURL.startsWith(experimentURL); | |
} | |
const finalURL = getFinalURL(currentURL, targetURL, experimentURL); | |
// If final constructed URL looks correct, and is within sample rate, then do the redirect. | |
if (isValidURL(finalURL, experimentURL) && isWithinSampleRate(SAMPLE_RATE)) { | |
return Response.redirect(finalURL, 302) | |
} | |
// Else return the original request. | |
else { | |
return await fetch(request) | |
} | |
} | |
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment