Skip to content

Instantly share code, notes, and snippets.

@Janpot
Last active June 7, 2018 10:52
Show Gist options
  • Save Janpot/ad0d05396790a3a6965f3389a6d88183 to your computer and use it in GitHub Desktop.
Save Janpot/ad0d05396790a3a6965f3389a6d88183 to your computer and use it in GitHub Desktop.
import { serve, Response } from 'some-http-lib'
serve(3000, async ({ request }) => {
const body = JSON.stringify({ hello: 'world' });
return new Response(body, {
status: 200,
headers: new Headers({
'content-type': 'application/json'
})
});
});
// middleware
function log (handler) {
return async ({ request, ...props }) => {
const start = Date.now();
const response = await handler({ request, ...props });
const end = Date.now();
console.log(`Request: ${request.method} ${request.url.pathname} (${end - start}ms)`)
return response;
};
}
// poor man's router
function route (routes) {
return ({ request, ...props }) => {
const handler = routes[request.url.path] || () => new Response(null, { status: 404 });
return handler({ request, ...props });
}
}
serve(3000, log(route({
'/hello': async () => new Response('world'),
'/world': async () => Response.redirect('/hello'),
'/echo': async ({ request }) => new Response(request.url.path)
})));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment