Skip to content

Instantly share code, notes, and snippets.

@kyanny
Created October 7, 2021 16:50
Show Gist options
  • Save kyanny/907dcc71745901cb794964fb9ccd9b6c to your computer and use it in GitHub Desktop.
Save kyanny/907dcc71745901cb794964fb9ccd9b6c to your computer and use it in GitHub Desktop.
Deno HTTP server for debug/echo
#!/usr/bin/env deno run --allow-net
// https://deno.land/manual/examples/http_server
// Start listening on port 8080 of localhost.
const server = Deno.listen({ port: 8080 });
console.log(`HTTP webserver running. Access it at: http://localhost:8080/`);
// Connections to the server will be yielded up as an async iterable.
for await (const conn of server) {
// In order to not be blocking, we need to handle each connection individually
// without awaiting the function
serveHttp(conn);
}
async function serveHttp(conn: Deno.Conn) {
// This "upgrades" a network connection into an HTTP connection.
const httpConn = Deno.serveHttp(conn);
// Each request sent over the HTTP connection will be yielded as an async
// iterator from the HTTP connection.
for await (const requestEvent of httpConn) {
const resp : string[] = [];
resp.push('='.repeat(120));
// The native HTTP server uses the web standard `Request` and `Response`
// objects.
for (const [key, value] of requestEvent.request.headers.entries()) {
resp.push(`${key}: ${value}`);
}
resp.push('');
const body = await requestEvent.request.body?.getReader().read()
const text = new TextDecoder().decode(body?.value);
if (requestEvent.request.headers.get('content-type') === 'application/json') {
resp.push(JSON.stringify(JSON.parse(text), null, 2));
} else {
resp.push(text);
}
console.log(resp.join("\n"));
// The requestEvent's `.respondWith()` method is how we send the response
// back to the client.
requestEvent.respondWith(
new Response(resp.join("\n"), {
status: 200,
}),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment