Created
May 9, 2024 06:58
-
-
Save itosho/60dbb9b579d35e805ba5df134a4c5770 to your computer and use it in GitHub Desktop.
Reverse Proxy in Cloudflare Wokers
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
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)); | |
}); | |
async function handleRequest(request) { | |
try { | |
const url = new URL(request.url); | |
// リダイレクト処理 | |
if (url.pathname.startsWith('/redirect/')) { | |
return handleRedirect(url); | |
} | |
// ヘルプページの表示 | |
if (url.pathname === '/') { | |
return showUsage(url); | |
} | |
// CORSプリフライトリクエストの処理 | |
if (request.method === 'OPTIONS') { | |
return handlePreflight(); | |
} | |
// APIリクエストの処理 | |
return handleApiRequest(request, url); | |
} catch (e) { | |
return new Response(e.stack || e, { status: 500 }); | |
} | |
} | |
function handleRedirect(url) { | |
let targetUrl = url.pathname.slice(10); | |
if (url.search) { | |
targetUrl += url.search; | |
} | |
return Response.redirect(targetUrl, 302); | |
} | |
function showUsage(url) { | |
return new Response(` | |
Usage:\n | |
${url.origin}/<url> | |
`, { | |
headers: { | |
'Content-Type': 'text/plain' | |
} | |
}); | |
} | |
function handlePreflight() { | |
return new Response(null, { | |
status: 200, | |
headers: { | |
'Access-Control-Allow-Origin': '*', | |
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS', | |
'Access-Control-Allow-Headers': 'Authorization, Content-Type, Notion-Version', | |
}, | |
}); | |
} | |
async function handleApiRequest(request, url) { | |
const headers = new Headers(request.headers); | |
// Notion API の特別なヘッダー処理 | |
if ('api.notion.com' === new URL(request.url.slice(url.origin.length + 1)).hostname && !headers.has('Notion-Version')) { | |
headers.set('Notion-Version', '2022-06-28'); | |
} | |
let response = await fetch(request.url.slice(url.origin.length + 1), { | |
method: request.method, | |
headers: headers, | |
redirect: 'follow', | |
body: request.body, | |
}); | |
response = new Response(response.body, response); | |
response.headers.set('Access-Control-Allow-Origin', '*'); | |
return response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment