Last active
March 14, 2024 05:39
-
-
Save digitigradeit/30b0aa31b3615e92ac63ee3af4a0fbe2 to your computer and use it in GitHub Desktop.
Cloudflare worker script to redirect to image (if it exist, or fallback URL), or redirect to random unsplash
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
// IMAGE URL / FALL BACK IMAGE / RANDOM UNSPLASH IMAGE REDIRECT USING CLOUDFLARE WORKER | |
// Version 0.1 - 2024-03-13 - Initial Script | |
// TODO (TBD): Check CORS, among other things, perhaps some caching, rate limiting, etc. | |
// Created by Brian Johnson - [email protected] https://brianjohnson.io | |
// Github Gist: https://gist.github.com/digitigradeit/30b0aa31b3615e92ac63ee3af4a0fbe2 | |
// USAGE: http://api.cloudflareworker.com/image?url=[URL-ENCODED IMAGE URL]&fallback=[URL-ENCODED FALLBACK URL] | |
// http://api.cloudflareworker.com/image?url=[URL-ENCODED IMAGE URL]&random=true&q=fruit | |
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
async function handleRequest(request) { | |
const urlParams = new URL(request.url).searchParams; | |
const imageUrl = urlParams.get('url'); | |
const fallbackUrl = urlParams.get('fallback'); | |
const query = urlParams.get('q'); | |
const random = urlParams.get('random') === 'true'; | |
// Check if the image URL exists | |
if (imageUrl) { | |
const response = await fetch(imageUrl, { method: 'HEAD' }); | |
if (response.ok) { | |
// Image exists, redirect to it | |
return Response.redirect(imageUrl, 302); | |
} | |
} | |
// Since the image (above) does not exist, if random=true redirect to unsplash, otherwise, use the fallback URL | |
if (fallbackUrl && !random) { | |
return Response.redirect(fallbackUrl, 302); | |
} else { | |
const unsplashUrl = `https://source.unsplash.com/random${query ? '?'+encodeURIComponent(query) : ''}`; | |
return Response.redirect(unsplashUrl, 302); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment