How to create a routing process with Deno's standard HTTP module

overview

I will show you how to easily use the routing function using Deno’s standard HTTP module. Routing is defined by specifying endpoints for handling HTTP requests.

Below, we’ll explore routing concepts, defining routes, creating route handlers, handling routing parameters, and options for routes in more detail.

Here, we will explain the routing method using the following versions.

Deno v1.16.0

In addition, all the code created this time is posted on GitHub.

How to create a route

Routing defines how a Deno application handles requests from clients when they reach a particular endpoint.

Routing is defined by a combination of HTTP methods (GET, POST, PUT, DELETE, etc.) and paths (URLs).

The code below uses Deno’s standard HTTP module to create a basic routing for handling HTTP requests.

routing.ts

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

const server = serve({ port: 8000 });
console.log("HTTP webserver running on: http://localhost:8000/");

for await (const request of server) {
  if (request.method === "GET" && request.url === "/") {
    request.respond({ body: "Hello, from the homepage!" });
  } else if (request.method === "GET" && request.url === "/about") {
    request.respond({ body: "Hello, from the about page!" });
  } else {
    request.respond({ status: 404, body: "Page not found" });
  }
}

Commentary

  • Create and start HTTP server
const server = serve({ port: 8000 });
console.log("HTTP webserver running on: http://localhost:8000/");

Here, an HTTP server is created using the serve function of Deno’s standard HTTP module and started on port 8000.

  • Define routing
for await (const request of server) {
  if (request.method === "GET" && request.url === "/") {
    request.respond({ body: "Hello, from the homepage!" });
  } else if (request.method === "GET" && request.url === "/about") {
    request.respond({ body: "Hello, from the about page!" });
  } else {
    request.respond({ status: 404, body: "Page not found" });
  }
}

When a server receives a request, it returns an appropriate response based on the HTTP method and URL of the request. This example handles requests for the “/” and “/about” paths for the GET method, and returns a 404 error for all other requests.

test

# test GET request
curl -X GET http://localhost:8000/
curl -X GET http://localhost:8000/about
curl -X GET http://localhost:8000/notfound

summary

In this article, you learned about routing. Routing is the process of selecting the appropriate handler based on the request’s path and HTTP method. Implementing routing makes it easier to implement a Web API. Next time, we will implement a simple Web API using routing.