Last active
January 27, 2020 06:13
-
-
Save acid-chicken/18a08c03f46759780f5be9321b3e8acc to your computer and use it in GitHub Desktop.
Hello World on Cloudflare Workers with simple router
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
/// <reference lib="webworker" /> | |
addEventListener('fetch', onFetch) | |
/** | |
* @arg {FetchEvent} event | |
*/ function onFetch(event) { | |
event.respondWith(handleRequest(event.request)) | |
} | |
const mnt = new URL('https://mountpoint-subdomain-goes-here.example.com/') | |
/** | |
* @arg {String} location | |
*/ function http301(location) { | |
return new Response('', { | |
headers: { | |
'Location': location | |
}, | |
status: 301, | |
}) | |
} | |
/** | |
* @arg {String} location | |
*/ function http308(location) { | |
return new Response('', { | |
headers: { | |
'Location': location | |
}, | |
status: 308, | |
}) | |
} | |
/** | |
*/ function http404() { | |
return new Response('', { | |
status: 404, | |
}) | |
} | |
/** | |
* @arg {String[]} allow | |
*/ function http405(...allow) { | |
return new Response('', { | |
headers: { | |
'Allow': allow.join(), | |
}, | |
status: 405, | |
}) | |
} | |
/** | |
* @arg {Request} request | |
*/ async function handleRequest(request) { | |
const { origin, pathname } = new URL(request.url) | |
if (origin != mnt.origin) { | |
switch (request.method) { | |
case 'GET': | |
case 'HEAD': return http301(mnt.origin + pathname) | |
default: return http308(mnt.origin + pathname) | |
} | |
} | |
switch (pathname) { | |
case '/': switch (request.method) { | |
case 'GET': return index() | |
default: return http405('GET') | |
} | |
default: return http404() | |
} | |
} | |
function index() { | |
return new Response(`<!DOCTYPE html> | |
<html lang="en"> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width,initial-scale=1.0"> | |
<title>Hello, world!</title> | |
Hello, world!`, { | |
headers: { | |
'Content-Type': 'text/html;charset=UTF-8', | |
}, | |
status: 200, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment