Skip to content

Instantly share code, notes, and snippets.

@dustinrouillard
Created July 26, 2020 07:05
Show Gist options
  • Save dustinrouillard/3d3911e0905da1b162313e3b4edaf213 to your computer and use it in GitHub Desktop.
Save dustinrouillard/3d3911e0905da1b162313e3b4edaf213 to your computer and use it in GitHub Desktop.
Cloudflare worker which runs flax.pics
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
});
const default_image = 'https://i0.wp.com/images-prod.healthline.com/hlcmsresource/images/AN_images/flaxseeds-1296x728-feature.jpg?w=1155&h=1528';
const flaxes = [
"https://i0.wp.com/images-prod.healthline.com/hlcmsresource/images/AN_images/flaxseeds-1296x728-feature.jpg?w=1155&h=1528",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT6rY8sUlsTvYmlY_Pb_IY8-n3VDlGUiX02Eg&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTvw3pLRTTi_7mHbUhVIAK4nrIft3TutGEw7w&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTq9yGFnyVm3Cazw6p6h287w3HcYWqNjTIfug&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQai6G7o8I8uDoJ0It7BIDX_zyRFDue61ry1g&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRCwB_H6yQsvgiR23zc3sibmB0toyUFknrV1w&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcR8s7AztwNgCHNym9shgM-m926qCM-Uc0P9yw&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQTHV2hd7kFad-4k2W26Rt2ZcwZcyjghFcPwQ&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRzuRH63PQUK1CocBV3fku-PWEa6QgCz-rJQw&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTVGupbtgzjvYhq050GL6l_Kp3ajeC_EwtAvQ&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSQ1t2CdHK_WKMjZHH6kmRM2XtU9PO4dgpwuw&usqp=CAU"
];
async function fetchImage() {
const imageUrl = flaxes[Math.floor(Math.random() * flaxes.length)];
let imageFile = await fetch(imageUrl);
let type = imageFile.headers.get('content-type');
if (type.includes('text/plain')) {
imageUrl = default_image;
imageFile = await fetch(default_image);
type = imageFile.headers.get('content-type');
}
let { readable, writable } = new TransformStream();
imageFile.body.pipeTo(writable);
return { url: imageUrl, file: readable, type };
}
async function handleRequest(request) {
const { url, file, type } = await fetchImage();
return new Response(file, {
headers: {
'x-original-url': url,
'content-type': type
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment