Skip to content

Instantly share code, notes, and snippets.

@acid-chicken
Last active January 27, 2020 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acid-chicken/18a08c03f46759780f5be9321b3e8acc to your computer and use it in GitHub Desktop.
Save acid-chicken/18a08c03f46759780f5be9321b3e8acc to your computer and use it in GitHub Desktop.
Hello World on Cloudflare Workers with simple router
/// <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