Skip to content

Instantly share code, notes, and snippets.

@nickturrietta
Last active April 3, 2020 05:13
Show Gist options
  • Select an option

  • Save nickturrietta/673c2ac94cb2e52e5cd7f1cf5060e80b to your computer and use it in GitHub Desktop.

Select an option

Save nickturrietta/673c2ac94cb2e52e5cd7f1cf5060e80b to your computer and use it in GitHub Desktop.
Cloudflare Worker - Round Robin Proxy With Cookies
const COOKIE_DOMAIN = 'www.sdrock.com';
const COOKIE_NAME = 'proxy_url_target';
const URLS = [
'https://www.sdrock.com/ministries/childrens/',
'https://www.sdrock.com/ministries/mens/',
'https://www.sdrock.com/ministries/womens/',
'https://www.sdrock.com/ministries/youngadult/',
'https://www.sdrock.com/ministries/youth/',
];
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
async function handleRequest(event)
{
let cookiedUrl = getCookie(event.request, COOKIE_NAME)
let url = cookiedUrl || randomUrl()
let response = await fetch(url, event.request)
response = new Response(response.body, response)
if ( ! cookiedUrl ) {
response.headers.set('Set-Cookie', COOKIE_NAME + '=' + url + '; Max-Age=15; Secure; Domain=' + COOKIE_DOMAIN + '; Path=/');
}
return response
}
function randomUrl()
{
let int = randomInt(1, URLS.length);
return URLS[int-1];
}
function randomInt(min, max)
{
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getCookie(request, name)
{
let result = null
let cookieString = request.headers.get('Cookie')
if (cookieString) {
let cookies = cookieString.split(';')
cookies.forEach(cookie => {
let cookieName = cookie.split('=')[0].trim()
if (cookieName === name) {
let cookieVal = cookie.split('=')[1]
result = cookieVal
}
})
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment