Deno nuggets: Callback style HTTP server

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to use callback style with native HTTP server in Deno?

HTTP server(callbackHandler => {}, listenAddress);

To read more about native HTTP server in Deno, visit the article here.

Solution

Imports

To write an HTTP server using callback style, a function called serve needs to be imported from Deno’s standard library’s HTTP module:

import { serve } from "https://deno.land/std/http/mod.ts";

HTTP server

The callback style HTTP server can be written in two simple steps:

  • Step 1: Use serve to listen on a given address along with a callback that would be invoked for each incoming request
  • Step 2: Write a callback handler that would take a standard Request object and returns a standard Response object

Here is a very simple callback style HTTP server that sends 200 OK for all requests (just 2 lines of code):

import { serve } from "https://deno.land/std/http/mod.ts";async function reqHandler(req: Request) {
return new Response();
}
serve(reqHandler, { port: 8000 });

Here is a sample run:

> curl http://localhost:5000
HTTP/1.1 200 OK

Here is another example that extracts the entire text out of the request body and sends it back to the caller:

import { serve } from "https://deno.land/std/http/mod.ts";async function reqHandler(req: Request) {
return new Response(await req.text());
}
serve(reqHandler, { port: 8000 });

Here is a sample run:

> curl http://localhost:5000 -d 'Easy to use callback style code'
Easy to use callback style code

Here is another example that pipes the Request body into the Response body (similar to previous example):

import { serve } from "https://deno.land/std/http/mod.ts";async function reqHandler(req: Request) {
return new Response(req.body);
}
serve(reqHandler, { port: 8000 });

Here is the output of a sample run:

> curl http://localhost:5000 --data-binary '@./testdata/sample2.txt' 
Learning
Deno
Is
Fun!

--

--