Building a Simple HTTP Server with Deno: Step-by-Step Guide
Creating a simple HTTP server from scratch in Deno is quite straightforward, thanks to its native support for serving HTTP requests. Below is a step-by-step guide to building a basic HTTP server using Deno:
Step 1: Install Deno
Ensure you have Deno installed on your system. If not, you can install it by following the instructions on the official Deno website.
Step 2: Create the HTTP Server
-
Create a new directory for your project:
mkdir my_deno_http_server cd my_deno_http_server -
Create a file named
server.ts: -
Write the server code inside
server.ts:import { serve } from "https://deno.land/std@0.115.1/http/server.ts"; const port = 8000; const server = serve({ port }); console.log(`HTTP server is running on http://localhost:${port}/`); for await (const request of server) { const url = new URL(request.url); let responseText = ""; // Basic routing if (url.pathname === "/") { responseText = "Welcome to the Deno HTTP server!"; } else if (url.pathname === "/about") { responseText = "This is a sample Deno HTTP server."; } else { responseText = "404 Not Found"; } request.respond({ body: responseText }); } -
Run the server: Open a terminal in your project directory and execute the following command:
deno run --allow-net server.tsThe
--allow-netpermission is required because the script needs to access the network to run the HTTP server.
Step 3: Test the Server
-
Access the server in a web browser or via a tool like
curl:- Open a browser and visit http://localhost:8000/. You should see the message "Welcome to the Deno HTTP server!".
- Visit http://localhost:8000/about to see the message "This is a sample Deno HTTP server."
- Any other URL will return "404 Not Found".
-
You can also test using
curl:curl http://localhost:8000/ curl http://localhost:8000/about curl http://localhost:8000/unknown
This is a very simple server that can serve basic text responses based on the URL path. This example demonstrates how to handle different URL paths, a basic feature of routing, and serves as a starting point for building more complex HTTP solutions using Deno.