Created
January 4, 2023 13:30
-
-
Save cohan/1b154156c9c3d3b269581c940339ce3d to your computer and use it in GitHub Desktop.
Prototype / Example worker for Cloudflare that pulls from R2
This file contains hidden or 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
const corsHeaders = { | |
'Access-Control-Allow-Origin': '*', | |
'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS', | |
'Access-Control-Max-Age': '86400', | |
}; | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
const key = url.pathname.slice(1); | |
const object = await R2.get(key); | |
if (object === null) { | |
return new Response('Object Not Found', { status: 404 }); | |
} | |
let respHeaders = { | |
...corsHeaders, | |
// Allow all future content Request headers to go back to browser | |
// such as Authorization (Bearer) or X-Client-Name-Version | |
'Access-Control-Allow-Headers': request.headers.get('Access-Control-Request-Headers'), | |
'etag': object.httpEtag | |
}; | |
return new Response(object.body, { | |
headers: respHeaders, | |
}); | |
} | |
function handleOptions(request) { | |
// Make sure the necessary headers are present | |
// for this to be a valid pre-flight request | |
let headers = request.headers; | |
if ( | |
headers.get('Origin') !== null && | |
headers.get('Access-Control-Request-Method') !== null && | |
headers.get('Access-Control-Request-Headers') !== null | |
) { | |
// Handle CORS pre-flight request. | |
// If you want to check or reject the requested method + headers | |
// you can do that here. | |
let respHeaders = { | |
...corsHeaders, | |
// Allow all future content Request headers to go back to browser | |
// such as Authorization (Bearer) or X-Client-Name-Version | |
'Access-Control-Allow-Headers': request.headers.get('Access-Control-Request-Headers'), | |
}; | |
return new Response(null, { | |
headers: respHeaders, | |
}); | |
} else { | |
// Handle standard OPTIONS request. | |
// If you want to allow other HTTP Methods, you can do that here. | |
return new Response(null, { | |
headers: { | |
Allow: 'GET, HEAD, OPTIONS', | |
}, | |
}); | |
} | |
} | |
addEventListener('fetch', event => { | |
const request = event.request; | |
const url = new URL(request.url); | |
if (request.method === 'OPTIONS') { | |
// Handle CORS preflight requests | |
event.respondWith(handleOptions(request)); | |
} else if (request.method === 'GET' || request.method === 'HEAD') { | |
// Handle requests to the API server | |
event.respondWith(handleRequest(request)); | |
} else { | |
event.respondWith( | |
new Response(null, { | |
status: 405, | |
statusText: 'Method Not Allowed', | |
}) | |
); | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment