0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

サーバー

0
Posted at
import http from "http";

type Handler = (
  req: http.IncomingMessage,
  res: http.ServerResponse,
  url: URL
) => void | Promise<void>;

const routes = new Map<string, Handler>([
  ["GET /", homeHandler],
  ["GET /users", getUsersHandler],
  ["POST /users", createUserHandler],
]);

const server = http.createServer(async (req, res) => {
  const method = req.method ?? "GET";

  const url = new URL(
    req.url ?? "/",
    `http://${req.headers.host}`
  );

  const key = `${method} ${url.pathname}`;

  const handler = routes.get(key);

  if (!handler) {
    res.writeHead(404);
    res.end("Not Found");
    return;
  }

  await handler(req, res, url);
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?