Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A concept of Cloud Flare edge worker that is used for transferring beacons to beacon catcher server.
var beaconCatcherAddress = "https://rum.revampix.com/beacon/catcher.php"
addEventListener('fetch', event => {
event.respondWith(handle(event, event.request))
})
async function asyncFetch(request) {
let response = fetch(request)
.then(
function() {},
function() {}
);
return response;
}
async function handle(event, request) {
if (request.method === "OPTIONS") {
return handleOptions(request)
} else if (request.method === "GET" ||
request.method === "HEAD" ||
request.method === "POST") {
//Health check bypass check
if (request.url.indexOf('healthcheck') > -1) {
return await fetch(craftOriginRequest(request))
}
let beaconRequest = craftOriginRequest(request)
event.waitUntil(
asyncFetch(
beaconRequest
)
)
//We want instant response to our visitor's browser
let response = new Response('')
return response
} else {
return new Response(null, {
status: 405,
statusText: "Method Not Allowed",
})
}
}
function craftOriginRequest(request) {
let originalUrl = request.url
if (originalUrl.indexOf('workers.dev') > -1) {
// clone the URL from the old request
let url = new URL(request.url)
// set a new hostname on the URL
//url.hostname = "rum.revampix.com"
url.href = originalUrl.replace(/.+?\.workers\.dev\/?/, beaconCatcherAddress);
// construct a new Request object for the new URL,
// passing the old request as the initialization object.
newRequest = new Request(url, request)
return newRequest;
}
return request;
}
function handleOptions(request) {
if (request.headers.get("Origin") !== null &&
request.headers.get("Access-Control-Request-Method") !== null &&
request.headers.get("Access-Control-Request-Headers") !== null) {
// Handle CORS pre-flight request.
let origing = "*";
if (request.headers.get("Origin") !== null) {
origing = request.headers.get("Origin");
}
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": origing,
"Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, Keep-Alive, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers",
"Access-Control-Max-Age" : "86400"
}
})
} else {
// Handle standard OPTIONS request.
return new Response(null, {
headers: {
"Allow": "GET, HEAD, POST, OPTIONS",
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.