Last active
February 19, 2018 16:12
-
-
Save nicusX/646e66c2b26a512df129ac70e37949f1 to your computer and use it in GitHub Desktop.
Lambda@Edge A/B testing - Viewer Request
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
'use strict'; | |
const sourceCoookie = 'X-Source'; | |
const sourceMain = 'main'; | |
const sourceExperiment = 'experiment'; | |
const experimentTraffic = 0.5; | |
// Viewer request handler | |
exports.handler = (event, context, callback) => { | |
const request = event.Records[0].cf.request; | |
const headers = request.headers; | |
// Look for source cookie | |
if ( headers.cookie ) { | |
for (let i = 0; i < headers.cookie.length; i++) { | |
if (headers.cookie[i].value.indexOf(sourceCoookie) >= 0) { | |
console.log('Source cookie found. Forwarding request as-is'); | |
// Forward request as-is | |
callback(null, request); | |
return; | |
} | |
} | |
} | |
console.log('Source cookie has not been found. Throwing dice...'); | |
const source = ( Math.random() < experimentTraffic ) ? sourceExperiment : sourceMain; | |
console.log(`Source: ${source}`) | |
// Add Source cookie | |
const cookie = `${sourceCoookie}=${source}` | |
console.log(`Adding cookie header: ${cookie}`); | |
headers.cookie = headers.cookie || []; | |
headers.cookie.push({ key:'Cookie', value: cookie }); | |
// Forwarding request | |
callback(null, request); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment