Skip to content

Instantly share code, notes, and snippets.

Created Oct 7, 2021
What would you like to do?
Deno HTTP server for debug/echo
#!/usr/bin/env deno run --allow-net
// 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
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[] = [];
// 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}`);
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 {
// The requestEvent's `.respondWith()` method is how we send the response
// back to the client.
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