Intermediate
clideploy
HTTP Server: Routing
An example of a HTTP server that handles requests with different responses based on the incoming URL.
Import the http server from std/http.
!--frsh-copybutton:1-->
import { serve } from "https://deno.land/std@0.175.0/http/server.ts";
URL patterns can be used to match request URLs. They can contain named groups that can be used to extract parts of the URL, e.g. the book ID.
!--frsh-copybutton:2-->
const BOOK_ROUTE = new URLPattern({ pathname: "/books/:id" });
function handler(req: Request): Response {
Match the incoming request against the URL patterns.
!--frsh-copybutton:3-->
const match = BOOK_ROUTE.exec(req.url);
If there is a match, extract the book ID and return a response.
!--frsh-copybutton:4-->
if (match) {
const id = match.pathname.groups.id;
return new Response(`Book ${id}`);
}
If there is no match, return a 404 response.
!--frsh-copybutton:5-->
return new Response("Not found (try /books/1)", {
status: 404,
});
}
To start the server on the default port, call `serve` with the handler.
!--frsh-copybutton:6-->
console.log("Listening on http://localhost:8000");
serve(handler);
Run this example locally using the Deno CLI:
deno run --allow-net https://byexample-wwv03xf36j0g.deno.dev/http-server-routing.ts
Additional resources: